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?
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.
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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With