.contents()

.contents()返回类型:jQuery

描述:取得匹配的元素集合中每个元素的子元素,包括文本和注释节点。

Given a jQuery object that represents a set of DOM elements, the .contents() method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .contents() and .children() methods are similar, except that the former includes text nodes and comment nodes as well as HTML elements in the resulting jQuery object. Please note that most jQuery operations don't support text nodes and comment nodes. The few that do will have an explicit note on their API documentation page.

The .contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

Consider a simple <div> with a number of text nodes, each of which is separated by two line break elements (<br>):

1
2
3
4
5
6
7
8
9
10
<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 employ the .contents() method to help convert this blob of text into three well-formed paragraphs:

1
2
3
4
5
6
7
8
9
$( ".container" )
.contents()
.filter(function() {
return this.nodeType === 3;
})
.wrap( "<p></p>" )
.end()
.filter( "br" )
.remove();

This code first retrieves the contents of <div class="container"> and then filters it for text nodes, which are wrapped in paragraph tags. This is accomplished by testing the .nodeType property of the element. This DOM property holds a numeric code indicating the node's type; text nodes use the code 3. The contents are again filtered, this time for <br /> elements, and these elements are removed.

示例:

Find all the text nodes inside a paragraph and wrap them with a bold tag.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>contents demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello <a href="http://ejohn.org/">John</a>, how are you doing?</p>
<script>
$( "p" )
.contents()
.filter(function(){
return this.nodeType !== 1;
})
.wrap( "<b></b>" );
</script>
</body>
</html>

演示:

Change the background color of links inside of an iframe.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>contents demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<iframe src="" width="80%" height="600" id="frameDemo"></iframe>
<script>
$( "#frameDemo" ).contents().find( "a" ).css( "background-color", "#BADA55" );
</script>
</body>
</html>

演示: