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.
jQuery code to show the working of this method:
Example 1:
html
<!DOCTYPE html>
< html >
< head >
< script src =
</ 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 >
< p id = "p1" >Welcome to GeeksforGeeks !!!</ p >
</ div >
< button >Click Me!</ button >
< br >
</ body >
</ html >
|
Output:

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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
07 Jul, 2023
Like Article
Save Article