Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Why?

like image 500
matt Avatar asked Feb 15 '11 12:02

matt


People also ask

What is closest in jQuery?

The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.

What are the jQuery selectors?

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

How can I find previous siblings in jQuery?

jQuery prev() Method The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.

How do I find a specific parent in jQuery?

The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.


1 Answers

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');
like image 142
BoltClock Avatar answered Sep 20 '22 23:09

BoltClock