The jQuery children() method can be used to return all or specified children of the selected element. You can find the immediate children of the required children of the selected element.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the element to select all direct children of the element. You can use the element tag name, class name, or id to select. It is a required field. |
selectorExpression | It is the selector expression to get the related children of the element. Optional field. |
jQuery children() Method to Return Direct Children
If you want to return all the direct children of the element, you have to use the method as given below. The example selects all the list items and return its text content. There are three list items and the method collects all the list element children.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ alert($("ul").children().text()); }); }); </script> <ul> <li>First li item.</li> <li>Second li item.</li> <li>Third li item.</li> </ul> <button type="button" class="mybtn">Click to Get Children</button> |
Output
- First li item.
- Second li item.
- Third li item.
You have to click the button given above to get all the children of the select list element. It displays an alert box that contains all the list element text content.
Return Specified Direct Children of the Element
The jQuery children() method can also be used to get only the specified item of the selected element. The below example contains the div element and it contains paragraph elements inside it. It selects the first item of the list element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<script> $(document).ready(function(){ $('.mydivbtn').click(function(){ $("div").children("p:first").css("color","orange"); }); }); </script> <div> <p>1st para item.</p> <p>2nd para item.</p> <p>3rd para item.</p> </div> <button type="button" class="mydivbtn">Click to Return Children</button> |
Output
1st para item.
2nd para item.
3rd para item.
When you click the button given above, the method selects the first list item. After that, it applies the orange color to the first item of the list element.
You may also like to read
I hope you like this tutorial on jQuery children() method. If you have any queries regarding the tutorial, please comment below.
References