- jQuery Tutorial
- jQuery - Home
- jQuery - Overview
- jQuery - Basics
- jQuery - Syntax
- jQuery - Selectors
- jQuery - Events
- jQuery - Attributes
- jQuery - AJAX
- jQuery DOM Manipulation
- jQuery - DOM
- jQuery - Add Elements
- jQuery - Remove Elements
- jQuery - Replace Elements
- jQuery CSS Manipulation
- jQuery - CSS Classes
- jQuery - Dimensions
- jQuery - CSS Properties
- jQuery Traversing
- jQuery - Traversing
- jQuery - Traversing Ancestors
- jQuery - Traversing Descendants
- jQuery References
- jQuery - Selectors
- jQuery - Events
- jQuery - Effects
- jQuery - HTML/CSS
- jQuery - Traversing
- jQuery - Miscellaneous
- jQuery - Properties
- jQuery - Utilities
- jQuery Plugins
- jQuery - Plugins
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery Useful Resources
- jQuery - Questions and Answers
- jQuery - Quick Guide
- jQuery - Useful Resources
- jQuery - Discussion
jQuery contents() Method
The contents() method in jQuery is used to retrieve the child nodes, including text and comment nodes, of each element in the set of matched elements.
Unlike the children() method, contents() includes text nodes and comment nodes.
Syntax
Following is the syntax of contents() method in jQuery −
$(selector).contents()
Parameters
This method does not accept any parameters.
Example
In the following example, we are using the contents() method to select all the text nodes inside the <div> element and wrap them with a span element of background color yellow −
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("div").contents().filter(function() { return this.nodeType === 3; // Filter for text nodes }).wrap("<span style='background-color: yellow;'/>"); }); }); </script> </head> <body> <div>Hello world! This is a beautiful day!</div> <br> <button>Click me</button><br> </body> </html>
After clicking the button, the content inside the <div> element will be wraped with a span element of yellow background color.
jquery_ref_traversing.htm
Advertisements