.contents()


.contents()傳回: jQuery

說明: 取得匹配元素集合中每個元素的子元素,包括文字和註解節點。

針對表示一組 DOM 元素的 jQuery 物件,.contents() 方法讓我們得以在 DOM 樹中搜尋這些元素的直接子元素,並從匹配元素建構新的 jQuery 物件。.contents().children() 方法很類似,但前者會在結果的 jQuery 物件中包含文字節點和註解節點,以及 HTML 元素。請注意,大多數 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
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-3.7.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>

示範

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

示範