Example
Return elements that are direct children of <ul>:
$(document).ready(function(){
$("ul").children().css({"color": "red", "border": "2px
solid red"});
});
Result:
body (great-grandparent)
div (grandparent)
ul (parent)
- li (child)
span (grandchild)
Try it Yourself »
Definition and Usage
The children() method returns all direct children of the selected element.
The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
Tip: To traverse a single level up the DOM tree, or all the way up to the document's root element (to return parents or other ancestors), use the parent() or parents() method.
Note: This method does not return text nodes. To return all children including text nodes, use the contents() method.
Syntax
$(selector).children(filter)
Parameter | Description |
---|---|
filter | Optional. Specifies a selector expression to narrow down the search for children |
Try it Yourself - Examples
Return all direct children of <ul>
How to return all direct children of an <ul> element.
Narrow down the search
How to use the filter parameter to
return all <li> elements with the class name "first", that are direct children of <ul>.
Return all <p> elements that are direct children of <div>
How to select all <p> elements that are direct children of their parent <div> element.
Show
the descendants of an element by tag names
A demonstration which shows who the
descendants of a <div> element
actually are.