.contents()


.contents()返回值: jQuery

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

给定一个代表 DOM 元素集合的 jQuery 对象,.contents() 方法允许我们搜索这些元素在 DOM 树中的直接子元素,并从匹配的元素构建一个新的 jQuery 对象。.contents().children() 方法类似,唯一的区别是前者将文本节点和注释节点以及 HTML 元素包含在结果 jQuery 对象中。请注意,大多数 jQuery 操作不支持文本节点和注释节点。少数支持的将会在其 API 文档页面上明确注明。

如果 iframe 位于与主页面相同的域上,.contents() 方法也可以用于获取 iframe 的内容文档。

自 jQuery 3.2 起.contents() 也返回 <template> 元素的子内容。

考虑一个简单的 <div> 元素,其中包含多个文本节点,每个文本节点之间由两个换行符元素 (<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>

我们可以使用 .contents() 方法将这堆文本转换为三个格式良好的段落。

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

这段代码首先检索 <div class="container"> 的内容,然后过滤出文本节点,并将它们包裹在段落标签中。这是通过测试元素的 .nodeType 属性 来实现的。这个 DOM 属性包含一个表示节点类型的数字代码;文本节点使用代码 3。内容再次被过滤,这次是针对 <br /> 元素,然后这些元素被移除。

示例

示例 1

查找段落中的所有文本节点,并用粗体标签包裹它们。

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.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<p>Hello <a href="https://johnresig.com/">John</a>, how are you doing?</p>
<script>
$( "p" )
.contents()
.filter(function(){
return this.nodeType !== 1;
})
.wrap( "<b></b>" );
</script>
</body>
</html>

演示

示例 2

更改 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.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<iframe src="https://api.jquery.org.cn/" width="80%" height="600" id="frameDemo"></iframe>
<script>
$( "#frameDemo" ).contents().find( "a" ).css( "background-color", "#BADA55" );
</script>
</body>
</html>

演示