levelup
levelup

Reputation: 11

Selecting the h2 element based on a clicked parent

I have a div called "panel" with multiple child elements, each with a class of poster. Each poster will be a card displaying restaurant information. I want to target the h2 for whichever poster the user clicks on, irrespective of which area of the poster they click. I'm using event delegation on the panel but I'm not sure how to target the h2.

HTML:

<div class="panel">

  <div class="poster">
    <div class="wrapper">
      <p class="time">6-7:30PM</p>
      <div class="inner-wrapper">
        <h2 class="restaurant-title">Restaurant A</h2>
        <h3 class="deal-description">bla bla bla</h3>
      </div>
    </div>
  </div>

    <div class="poster">
    <div class="wrapper">
      <p class="time">2-4:30PM</p>
      <div class="inner-wrapper">
        <h2 class="restaurant-title">Restaurant B</h2>
        <h3 class="deal-description">bla bla bla</h3>
      </div>
    </div>
  </div>

    <div class="poster">
    <div class="wrapper">
      <p class="time">1-5:30PM</p>
      <div class="inner-wrapper">
        <h2 class="restaurant-title">Restaurant C</h2>
        <h3 class="deal-description">bla bla bla</h3>
      </div>
    </div>
  </div>

</div>

JS:

var panel = document.querySelector(".panel");

panel.addEventListener("click", handleClick);

Upvotes: 0

Views: 103

Answers (4)

levelup
levelup

Reputation: 11

so i figured out a solution for this, and thought i'd share:

$(".poster").click(function(){

    var h2 = $(this).find('h2');

    var restaurantTitle = (h2["0"].innerText);

Upvotes: 0

freethinker
freethinker

Reputation: 2435

Try this :

$(document).ready(function(){
    $(".poster").click(function(){
       var h2 = $(this).children(".restaurant-title");    
        //alert(h2.context.innerText);
    })
})

Example on jsfiddle: https://jsfiddle.net/ar1xawku/ Don't forget include jquery library in your code

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

use queryselector() in javascript

 function handleClick(){
     var h2=this.querySelector("h2");
}

Demo

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82241

Using jquery:

$(".panel").click(function(){
   var h2 = $(this).find('h2');
});

Upvotes: 0

Related Questions