The contents() is an inbuilt method in jQuery that returns all the direct children, including text and comment nodes for the selected element.
Syntax:
$(selector).contents()
Parameter: It does not accept any parameter.
Return Value: It returns all the direct children elements of the selected element.
Code #1:
<html> <head> jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { <!-- jQuery code to perform this method --> $("button").click(function() { $("div").contents().filter("p").wrap("<b/>"); }); }); </script> <style> #p1 { width: 420px; padding: 50px; display: block; border: 2px solid green; font-size: 30px; } </style> </head> <body> <div> <!-- This paragraph will get bold after click on the button --> <p id="p1">Welcome to GeeksforGeeks !!!</p> </div> <!-- click on this button --> <button>Click Me!</button> <br> </body> </html> |
Output:
Before clicking the “Click Me!” button-

After clicking the “Click Me!” button-

Code #2:
In the below code, no need to click on any button.
<html> <head> <style> #p1 { display: block; width: 400px; padding: 30px; border: 2px solid green; font-size: 30px; } </style> </head> <body> <!-- This paragraph will get bold --> <p id="p1">Welcome to GeeksforGeeks !</p> <script> $("p") .contents() .filter(function() { return this.nodeType !== 1; }) .wrap("<b></b>"); </script> </body> </html> |
Output:

Recommended Posts:
- How to show contents of selected row of a table in Bootstrap model using jQuery ?
- How to load the contents of a text file into a JavaScript variable?
- jQuery | jQuery.fx.interval Property with example
- jQuery | jQuery.fx.off Property
- jQuery | jQuery.support Property
- jQuery | jquery Property
- jQuery | prepend() with Examples
- jQuery | dblclick() with Examples
- jQuery | offset() with Examples
- jQuery | children() with Examples
- jQuery | Hide/Show, Toggle and Fading methods with Examples
- jQuery | focusin() with Examples
- jQuery | Animation, Slide methods with Examples
- jQuery | change() with Examples
- jQuery | filter() with Examples
- jQuery | height() and innerHeight() with Examples
- jQuery | eq() with Examples
- jQuery | empty() with Examples
- jQuery | not() method with Examples
- jQuery | first() with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


