Home » jQuery children() method

jQuery children() method

by Online Tutorials Library

jQuery children() method

The children() method in jQuery returns the direct children of the given selector. It is an inbuilt method in JQuery. This method traverses only a single level down the DOM tree. We can use the find() method to traverse multiple levels down or return the descendants(such as grandchildren, great-grandchildren, etc.).

Suppose we have a jQuery object representing the set of elements, so the children() method search a level down in the DOM tree and construct a new jQuery object that contains the subset of matching elements.

The children() method doesn’t return text nodes. We can use the contents() method to get all children with text nodes.

The syntax of using the children() method is given as follows.

Syntax

This method accepts an optional parameter, i.e., filter.

filter: It is an optional value that is used to narrow down the search. It is a selector expression that can be of the same type as passing to the $() function.

Now, we will see some examples of using the children() method. In the first example, we are not using the optional parameter value, while in the second example, we are using the optional value to narrow down the search.

Example1

In this example, there is a div element along with two ul elements, a heading h2, and a paragraph element. Here, we are using the children() method to get the direct children of the div element. Both ul elements are the direct children of the div element so, the children() method will return both ul elements as the direct children of the div element.

We have to click the given button to see the effect.

Test it Now

Output

jQuery children() method

After clicking the given button, the output will be –

jQuery children() method

Now, in the next example, we will use the optional parameter of the children() method.

Example2

In this example, we are using the filter value to narrow down the search. Here, there are two ul elements, and both are the direct children of the div element. We are passing the first ul element with the class name first as the optional parameter of the children() method.

So, the method will return the corresponding ul element, which is now the prior child between all the children of the given selector.

Test it Now

Output

After the execution of the above code, the output will be –

jQuery children() method

On clicking the button, we can see that the function will return the element with the class name first. Here, the function will not return the second ul element, which is also the direct children of the div element.

After clicking the button, the output will be –

jQuery children() method


You may also like