Black friday

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

jQuery Children

Reading time 2 min
Published Dec 21, 2017
Updated Oct 1, 2019

If you need to get information on relations between HTML elements, jQuery .children() function retrieves children of specified elements. This method is different from .find() because .children() reaches only a single level down the DOM tree.

.find() method detects children while traversing down multiple levels. Therefore, the .find() method has a bigger scope. Furthermore, you should also consider adding selectors to the .children() jQuery function. If you decide to add them, the search looks for matches to the specified condition.

For instance, you can use jQuery nth child selectors which can count children from the last to first, select jQuery first child, or do other tasks that depend on sibling relations.

jQuery children: Main Tips

  • jQuery .children() method traverses downwards a single level of the DOM tree and looks for descendants of specified elements.
  • .children() jQuery function accepts selector expressions to make your search more specific.

.children() Explained

When traversing downwards, jQuery .children() returns all direct children and traverse one level down the DOM tree. Here is a code example to illustrate how this method is used:

Example
// returns all direct children
$(".content").children();

// returns all <p> elements that are direct children
$(".content").children("p");

The method returns the direct children of the element you select, and uses syntax like this:

$(selector).children([selector])

The optional selectors this method accepts are used to filter the children. jQuery nth child selectors can help you make your search more efficient. Here is a list of a few selectors you can add to the .children() jQuery function:

  • $(":nth-child(n)"): detects the nth children of the indicated parent elements.
  • $(":nth-last-of-type"): detects the nth children of the indicated parent elements, in relation to siblings of the same element name. It counts from the last child to the first.
  • $(":first-child"): detects the jQuery first child of parent elements.
  • $(":only-child"): detects elements that are the only children of their parents.

See a simple example of using both "p" and "p:nth-child(3n-1)" for assigning different background colors:

Example
$(document).ready(function () {
  $("p").css("background-color", "#ebf998");
  $("p:nth-child(3n-1)").css("background-color", "#8bbfef");
});

For more selectors to filter the .children() jQuery function, visit this tutorial.

jQuery children: Summary

  • The .children() jQuery finds children elements of specified parents by traversing through the DOM tree.
  • You can add selectors to make your search more specific and suitable for your needs.