jQuery Traversal - contents() Method
Example
Find all text nodes within the paragraphs and wrap them with bold tags.
$("p").contents().filter(function(){ return this.nodeType != 1; }).wrap("<b/>");
Definition and Usage
The contents() method gets the child nodes of each element in the matching element collection, including text and comment nodes.
Syntax
.contents()
Detailed Description
If a jQuery object representing a collection of DOM elements is given, the .contents() method allows us to retrieve the direct child nodes of these elements in the DOM tree and construct a new jQuery object with matching elements. The .contents() and .children() The method is similar, but the former includes both text nodes and HTML elements in the resulting jQuery object.
.contents() method can also be used to get the content document of an iframe, provided that the iframe is in the same domain as the main page.
Please consider the following <div> with some text nodes, each node is separated by two line break elements (<br>):
<div class="container"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. <br /><br /> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. <br /> <br /> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div>
We can use the .contents() method to convert text blocks into well-formed paragraphs:
$('.container').contents().filter(function() { return this.nodeType == 3; ) .wrap('<p></p>') .end() .filter('br') .remove();
This code first receives the content of <div class="container">, then filters its text nodes, and wraps them into paragraph tags. This is achieved by testing the element's .nodeType property, which contains a numeric code indicating the node type; text nodes use code 3. The content is filtered again, this time for <br /> elements, which are removed.