.not()


.not( selector )傳回:jQuery

說明:從匹配元素的集合中移除元素。

  • 新增版本:1.0.not( selector )

    • selector
      類型:選擇器元素陣列
      包含選擇器表達式、DOM 元素或元素陣列的字串,用於與集合進行比對。
  • 新增版本:1.4.not( function )

    • function
      類型:函式( 整數 index, 元素 element ) => 布林
      用於測試集合中每個元素的函式。它接受兩個參數,index,這是元素在 jQuery 集合中的索引,以及 element,這是 DOM 元素。在函式中,this 參照目前的 DOM 元素。
  • 版本新增:1.4.not( selection )

    • selection
      類型:jQuery
      現有的 jQuery 物件,用於比對目前一組元素。

給定一個表示一組 DOM 元素的 jQuery 物件,.not() 方法會從符合元素的子集中建構一個新的 jQuery 物件。提供的選擇器會針對每個元素進行測試;不符合選擇器的元素會包含在結果中。

考慮一個包含簡單清單的頁面

1
2
3
4
5
6
7
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

我們可以將此方法套用至清單項目組

1
$( "li" ).not( ":nth-child(2n)" ).css( "background-color", "red" );

此呼叫的結果會讓項目 1、3 和 5 變成紅色背景,因為它們不符合選擇器。

移除特定元素

.not() 方法的第二個版本允許我們從符合的組中移除元素,假設我們先前已透過其他方式找到這些元素。例如,假設我們的清單有一個 id 套用至其中一個項目

1
2
3
4
5
6
7
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li id="notli">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

我們可以使用原生 JavaScript getElementById() 函數擷取第三個清單項目,然後從 jQuery 物件中移除它

1
2
$( "li" ).not( document.getElementById( "notli" ) )
.css( "background-color", "red" );

此陳述會變更項目 1、2、4 和 5 的顏色。我們可以使用更簡單的 jQuery 表示式達成相同的效果,但此技術在其他函式庫提供純 DOM 節點參考時會很有用。

從 jQuery 1.4 開始,.not() 方法可以像 .filter() 一樣將函數當作引數。函數傳回 true 的元素會從篩選的組中排除;所有其他元素都會包含在內。

注意:當一個 CSS 選擇器字串傳遞給 .not() 時,在過濾處理過程中,文字和註解節點將永遠從結果的 jQuery 物件中移除。當提供特定節點或節點陣列時,文字或註解節點僅會在與過濾陣列中的節點之一相符時從 jQuery 物件中移除。

範例

為不是綠色或藍色的 div 新增一個邊框。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>not demo</title>
<style>
div {
width: 50px;
height: 50px;
margin: 10px;
float: left;
background: yellow;
border: 2px solid white;
}
.green {
background: #8f8;
}
.gray {
background: #ccc;
}
#blueone {
background: #99f;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<div></div>
<div id="blueone"></div>
<div></div>
<div class="green"></div>
<div class="green"></div>
<div class="gray"></div>
<div></div>
<script>
$( "div" ).not( ".green, #blueone" )
.css( "border-color", "red" );
</script>
</body>
</html>

示範

從所有段落的集合中移除 ID 為「selected」的元素。

1
$( "p" ).not( $( "#selected" )[ 0 ] );

從所有段落的集合中移除 ID 為「selected」的元素。

1
$( "p" ).not( "#selected" );

從所有段落的總集合中移除所有符合「div p.selected」的元素。

1
$( "p" ).not( $( "div p.selected" ) );