Member-only story
jQuery — Parent Elements
jQuery is a popular JavaScript for creating dynamic web pages.
In this article, we’ll look at how to using jQuery in our web apps.
.parents()
The .parents()
method lets us get the ancestors of each element in the current set of matched elements.
We can optionally filter that with a selector.
For example, if we have:
<ul class="level-1">
<li class="item-i">I</li>
<li class="item-ii">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
Then we get all the ancestors of the li
with the item-a
class by writing:
$("li.item-a").parents().css("background-color", "red");
Then we add a red background to it.
.parentsUntil()
The .parentsUntil()
method gets the ancestors of each element in the current set of matched elements up to but nor including the element matched bu the selector, DOM node, or jQuery object.