Like this

  • ...">

    JQuery: closest ('h3') selector?

    I have:

    <ul class="rating"> <h3>Like this</h3> <li class="rating-number"> <div id="iLikeThis" class="iLikeThis"> <span class="counter">2</span> </div> </li> </ul> 

    this is my jquery code

     $('.iLikeThis .counter').each(function() { $(this).parent().parent().parent().children('h3').text('You like this'); $(this).parent().addClass('like'); }); 

    Is there a better way to select the closest h3 element. It works with a 3x parent (), but not with the closest ("h3").

    Why?

    +7
    source share
    1 answer

    Since h3 not a parent of .counter , this will not work. Use .closest() on .rating and find its h3 :

     $(this).closest('.rating').children('h3').text('You like this'); 
    +13
    source

    All Articles