Babulaas
Babulaas

Reputation: 869

jQuery next, parent, closest

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();
});

Upvotes: 3

Views: 1245

Answers (3)

Seabizkit
Seabizkit

Reputation: 2415

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?

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337626

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.

Upvotes: 5

Milind Anantwar
Milind Anantwar

Reputation: 82241

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();
});

Upvotes: 0

Related Questions