Learn to use jQuery children method with examples

Learn to use jQuery children method with examples

Learn to use jQuery children method with examples

The children method

The children method is used to return the first level child of the specified element. This method searches only to the first level downward. In order to find all descendant elements, you can use the jQuery find method.

See an example of children method

To make it clearer, consider the following simple structure:


<p>some text

<span>some text</span>



In that case, the <p> is child of div element while <span> is grandchild or second level child of div element.

In the above structure, if you specify the div element while using the children method, it will search the paragraph only. Similarly, if you specify the paragraph it will find span element, which is the child of the paragraph.

add a CSS class by children method example

However, if you need to find and apply changes to all elements downward to that div (paragraph and span) then you should use the find method of jQuery.

Syntax of children method

The general syntax of children jQuery method is:


Where parent element can be a selector like a div, paragraph etc.

In the section below, we will show you examples of using the children method. We will use jQuery children method to change the first-level child element presentation.

Children example to add text to child element

In the following example, a div is a parent element of a paragraph. As you click on the button, it will add text at the end of the paragraph.

$.children add text

Experience this example online

First, we searched the first level child of div element by using the children method and then jQuery after method is used to add text.

The children example to add CSS to child element

The example below adds CSS by using jQuery children method.

children add CSS

Experience this example online

If you use <span> element rather <p> in the above example, it will not work. In order to impact all descendant elements use jQuery find method.

To go upwards, from child to parent level use jQuery parents method.

Example of children method to add class to a button

In this example, as we have a button which is the child of paragraph and grandchild of the div element. As you click on button “Run children method” it will add class to the button element.

jQuery children

Experience this example online

You can see, we used ‘P’ in the children method.

jQuery remove children example

You can use the remove method with jQuery children method to remove the first level child. In this example, as you click the button it will remove a button which is the child of the paragraph.

Experience this example online


Useful links: jQuery find | jQuery parents

Was this article helpful?