How to get a set of elements containing all of the unique immediate children of each of the matched set of elements?

The children( [selector] ) method gets a set of elements containing all of the unique immediate children of each of the matched set of elements. This method only traverses a single level down the DOM tree to find the direct children, unlike the find() method which searches through all descendant elements.

The optional selector parameter allows you to filter the children elements by CSS selector, class, ID, or element type.

Syntax

$(selector).children([filter])

Parameters:

  • filter (optional) ? A string containing a selector expression to match elements against

Example

You can try to run the following code to learn how to get a set of elements containing all of the unique immediate children of each of the matched set of elements ?

<!DOCTYPE html>
<html>
   <head>
      <title>jQuery Example</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function(){
            $("div").children(".selected").addClass("blue");
         });
      </script>
       
      <style>
         .blue {
            color: blue;
            font-weight: bold;
         }
      </style>
   </head>
   
   <body>
      <div>
         <span>Hello</span>
         <p class="selected">Hello Again</p>
         <div class="selected">And Again</div>
         <p class="biggest">And One Last Time</p>
      </div>
   </body>
</html>

In this example, the children(".selected") method finds only the immediate children of the div element that have the class "selected". The elements with class "selected" will be styled with blue color and bold font weight.

Conclusion

The children() method is useful for selecting direct child elements without traversing deeper into the DOM hierarchy. It provides an efficient way to target immediate children with optional filtering capabilities.

Updated on: 2026-03-13T18:15:24+05:30

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements