3

HTML:

<div class="container">
  <ul>
    <li class="item" id="id_1">
      <h2>header</h2>
      <div class="c_image">
        <img/>
      </div>
    </li>
  </ul>
</div>

Click event on images must trigger a click event on the related h2. The html is automatically rendered.

JS:

$(".container .item .c_image img").each(function(){
  $(this).click(function(){
    //console.log($(this).parent("li.item"));
    $(this).closest("h2")[0].click();
  });
});

What is the best solution is this situation, I tried closest but it doesn't trigger the h2 click event.

This works fine:

$('#id_1 .c_image img').click(function(){
  $('li#id_1 h2')[0].click();
});
Shikkediel
  • 5,195
  • 16
  • 45
  • 77
Babulaas
  • 761
  • 3
  • 13
  • 47

3 Answers3

5

closest('h2') won't work here as the h2 is a sibling of a parent the img element. You would need to get the closest li and then find() the h2:

$(".container .item .c_image img").click(function(){
    $(this).closest('li').find("h2").click();
});

Note that you don't need to iterate over the img elements and also that you could avoid the need for this code if you attach the event to the li instead of the h2 as the event would then bubble up from both the img and the h2.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

h2 element is previous sibling of clicked image parent. hence you can use .parent() along with .prev() selector

Also you don't need to iterate over elements individually to attach same event for them. you can simply bind the event to returned images object. Like this:

$(".container .item .c_image img").click(function(){
   $(this).parent().prev().click();
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

quote "Click event on images must trigger a click event on the related h2." Assuming that the same event must happen whether the img or the heading is clicked.

could you not place the click event on the li rather

$(".container li").on("click", function(){
    var $this = $(this);
    var heading = $this.find('h2').html();
    console.log(heading);
});

cannot suggest better than what others have already without further understanding of why?

Seabizkit
  • 2,417
  • 2
  • 15
  • 32