8

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 nearest h3 element. It does work with 3-times parent() but not with closest('h3).

Why?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
matt
  • 42,713
  • 103
  • 264
  • 397
  • 1
    This is invalid HTML. You can't have a `h3` as a child of a `ul`. With broken HTML like this, it's impossible to know if the browser does the right thing. – RoToRa Feb 15 '11 at 12:47
  • thanks! can you have it as a child of li? – matt Feb 15 '11 at 12:49

1 Answers1

16

As h3 is not a parent of .counter, that won't work. Use .closest() on .rating instead and find its h3:

$(this).closest('.rating').children('h3').text('You like this');
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356