Parents and Ancestors
Move up the DOM tree from a selected element.
Syntax
$(selector).parent(); $(selector).parents();Traversal methods move through the family tree of elements. To go up:
.parent()— the direct parent (one level up)..parents()— all ancestors up to the root..parents("div")— ancestors matching a selector.
Example
Loading editor…
Press Run to see the result.
When to use it
- A remove button walks up with .closest('li') to delete its entire list-item container, not just the button itself.
- A validation helper calls .parent() on an invalid input to add an .error class to the wrapping form group div.
- A drag-and-drop handler uses .parents('.droppable') to find all ancestor drop zones the dragged item sits inside.
More examples
Select the immediate parent element
.parent() selects only the direct parent of the matched element, here the .wrapper div.
<div class="wrapper">
<p id="inner">Hello</p>
</div>
<button id="highlight">Highlight parent</button>
<script>
$(function () {
$("#highlight").click(function () {
$("#inner").parent().css("border", "2px solid tomato");
});
});
</script>Walk up multiple levels with parents()
.parents() (plural) collects all ancestors in the tree; here it outlines every wrapping element at once.
<section>
<article>
<p id="text">Deep text</p>
</article>
</section>
<button id="markAncestors">Mark ancestors</button>
<script>
$(function () {
$("#markAncestors").click(function () {
$("#text").parents().css("outline", "1px dashed #999");
});
});
</script>Filter ancestors by selector
.parents(".form-group") stops at the first matching ancestor, adding the error class only to the correct wrapper.
<form>
<div class="form-group">
<input id="email" type="email" />
</div>
</form>
<button id="markGroup">Mark group</button>
<script>
$(function () {
$("#markGroup").click(function () {
$("#email").parents(".form-group").addClass("has-error");
});
});
</script>
Discussion