jQuery Descendants

jQuery Traversing Descendants, which is all about moving down the DOM tree from a selected element.


Traversing Down the DOM Tree

In jQuery, descendant traversal means selecting elements that are nested inside another element — children, grandchildren, great-grandchildren, and so on.


Two useful jQuery methods for traversing down the DOM tree are:

Method

Description

.children()

Selects immediate child elements only

.find()

Selects all descendants that match a selector

jQuery children() Method


The .children() method returns only the direct children of the selected element(s). It does not go deeper like .find().

This method only traverses a single level down the DOM tree.


The following example returns all elements that are direct children of each <div> elements:

Example
<script>
$(document).ready(function(){
$("div").children().css({"color": "red", "border": "2px solid red"});
});
</script>

Try it yourself

When using jQuery’s .children() method, you can also pass a selector as an optional parameter to filter which child elements you want to select.

The following example returns all <p> elements with the class name "first", that are direct children of <div>:

Example
<script>
$(document).ready(function(){
$("div").children("p.first").css({"color": "red", "border": "2px solid red"});
});
</script>

Try it yourself

jQuery find() Method


The .find() method searches downward in the DOM tree and returns all descendant elements of the selected element that match the given selector — no matter how deeply nested.


The following example returns all <span> elements that are descendants of <div>:

Example
<script>
$(document).ready(function(){
$("div").find("span").css({"color": "red", "border": "2px solid red"});
});
</script>

Try it yourself

The following example returns all descendants of <div>:

Example
<script>
$(document).ready(function(){
$("div").find("*").css({"color": "red", "border": "2px solid red"});
});
</script>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.