The jQuery contents() method can be used to return all the direct children of the selected element. It also includes the text and comment nodes of the specified 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 and return all direct children of it. You can use the element tag name, class name, or id to select. It is a required field. |
jQuery contents() Method to Return All Direct Children’s
If you want to get all direct children of the element including its text, you have to use the method as given below. The example contains the list of elements and the button element. It checks for the span elements if present and wrap it inside the em element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("ul li").contents().filter("span").wrap("<em/>").css("color","orange"); }); }); </script> <ul> <li>First li item.</li> <li>Second li item.</li> <li><span>Third li item.</span></li> <li>Forth li item.</li> <li>Fifth li item.</li> </ul> <button type="button" class="mybtn">Click to Return</button> |
Output
- First li item.
- Second li item.
- Third li item.
- Forth li item.
- Fifth li item.
You have to click the button given above to return the children of the selected element. After selecting the element, it checks for the span element and make it italic. It also applies the orange color to it o highlight the element. The above example uses the jQuery filter(), wrap(), and css() method.
You may also like to read
I hope you like this tutorial on jQuery contents() method. If you have any queries regarding the tutorial, please comment below.
References