jQuery Traversal - children() Method

Instance

Find all child elements of divs with the class name "selected" and set them to blue:

$("div").children(".selected").css("color", "blue");

Try it yourself

Definition and Usage

The children() method returns all direct child elements of the selected elements.

Syntax

.children(selector)
Parameter Description
selector String value, containing the selector expression that matches the elements.

Detailed Description

If a jQuery object representing a collection of DOM elements is given, the .children() method allows us to retrieve these elements from the DOM tree and construct a new jQuery object with matching elements..find() Similar to the .children() method, but the latter only traverses a single level down the DOM tree.

Note that, like most jQuery methods, .children() does not return text nodes; if you need to get all child nodes including text and comment nodes, please use .contents().

This method accepts an optional selector expression, which is of the same type as the parameters passed to $(). If the selector is applied, it will test whether the elements match the expression, thereby filtering these elements.

Consider this page with a basic nested list:

<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>

Try it yourself

If we start from the level-2 list, we can find its child elements:

$('ul.level-2').children().css('background-color', 'red');

The result of this line of code is that items A, B, C get a red background. Since we did not apply a selector expression, the returned jQuery object contains all child elements. If a selector is applied, it will only include matching items.