jQuery children() Method



The children() method in jQuery is used to select all direct child elements of the selected element(s). It traverses down the DOM tree to find the children elements that are immediate descendants of the selected element(s). It does not traverse all descendants, only the immediate children.

Note:If we want to traverse deep down and return grandchildren or other descendants, we need to use the find() method.

Syntax

Following is the syntax of children() method in jQuery −

$(selector).children(filter)

Parameters

This method accepts the following optional parameter −

  • filter: A string containing a selector expression to filter the children elements.

Example 1

In the following example, we are using the children() method to return elements that are direct children of <ul> −

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $("ul").children().css("color", "#40a944");
      });
  </script>
</head>
<body>
  <ul>Parent
    <li>children 1</li>
    <li>children 2</li>
    <li>children 3</li>
    <li>children 4</li>
  </ul>
</body>
</html>

When we execute the above program, the children() method returns all the elements under the <ul> element and changes its color to green.

Example 2

Here, we are select all the li elements with class 'one"' that are direct children of their parent ul element −

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $("ul").children(".one").css("color", "#40a944");
      });
  </script>
</head>
<body>
  <ul>Parent
    <li>child 1</li>
    <li class="one">child 2</li>
    <li class="one">child 3</li>
    <li class="second">child 4</li>
  </ul>
</body>
</html>

After executing the above program, the li elements with class 'one' will be returned with green colored text.

Example 3

In this example below, we are selecting all the span elements that are direct children of their parent div element −

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $("div").children("p").css("color", "#40a944");
      });
  </script>
</head>
<body>
  <div>Parent
    <p>paragraph: child</p>
    <span>span: child</span>
    <p>paragraph: child</p>
    <span>span: child</span>
    <p>paragraph: child</p>
  </div>
</body>
</html>

When we execute the above program, the children() method returns all the span elements that are direct children to div and changes its color to green.

jquery_ref_traversing.htm
Advertisements