jQuery .contents() returns the children tags and text nodes
Syntax and Description
.contents()
gets the children of each element in the set of matched elements, including text nodes.
Return value is the new jQuery object.
Get the content of a paragraph
The following code gets the child tags from a paragraph and then it converts them to text.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- w w w . j ava 2 s .c o m-->
alert($("p").contents().text());
});
</script>
</head>
<body>
<body>
<p>Hello <span>span</span>data java 2s.com</p>
</body>
</html>
Wrap the content of a paragraph
The following code gets the children tags and text
nodes for a paragraph. And then uses the filter method
to wrap content with <br/>
.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- w w w . ja v a 2s .c om-->
$("p").contents().filter(function(){ return this.nodeType != 1; }).wrap("<br/>");
});
</script>
</head>
<body>
<body>
<p>Hello <span>span</span>data java 2s .c om</p>
</body>
</html>