开发者

jquery: closest('h3') selector?

开发者 https://www.devze.com 2023-02-11 02:41 出处:网络
i have: <ul class=\"rating\"> <h3>Like this</开发者_JS百科h3> <li class=\"rating-number\">

i have:

<ul class="rating">
    <h3>Like this</开发者_JS百科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?


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');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号