jquery
  1. jquery-children

jQuery children()

The children() method in jQuery is used to retrieve all the direct child elements of the selected parent element.

Syntax

The syntax for the children() method is as follows:

$(selector).children(filter)

Here, selector is the parent element that you want to retrieve the children of, and filter is an optional parameter to filter the child elements based on a specific criteria.

Use

The children() method is useful when you want to access the direct child elements of a selected parent element. This can be helpful when you need to manipulate or perform actions on specific child elements, such as adding a class or changing the text content.

Example

Here is an example of using the children() method to retrieve all of the direct child elements of a parent ul element:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <style>
    /* Optional: Some styling to visualize the color change */
    #parent > li {
      border: 1px solid black;
      margin: 5px;
      padding: 5px;
    }
  </style>
</head>
<body>

  <ul id="parent">
    <li>Child 1</li>
    <li>Child 2</li>
    <li>Child 3</li>
  </ul>

  <script>
    $(document).ready(function(){
        $("#parent").children().css("color", "red");
    });
  </script>

</body>
</html>
Try Playground

In this example, we use the children() method to select all the direct child elements of the ul element with the ID of "parent". We then use the .css() method to change the text color of each child element to red.

Summary

The children() method in jQuery is a useful tool for selecting and manipulating the direct child elements of a parent element. It allows you to easily perform actions on child elements without having to select them individually. Try using children() in your next jQuery project!

Published on: