:has() 選擇器


has 選擇器

說明:選取包含至少一個符合指定選擇器的元素的元素。

  • 新增版本:1.1.4jQuery( ":has(selector)" )

    選擇器:任何選擇器。

表達式 $( "div:has(p)" ) 會在 <div> 中存在 <p> 的情況下,與 <div> 匹配,而並非僅在 <p> 為其直接子元素的情況下。

其他注意事項

  • 由於 :has() 是 jQuery 擴充功能,而非 CSS 規格的一部分,因此使用 :has() 的查詢無法利用原生 DOM querySelectorAll() 方法提供的效能提升。若要在現代瀏覽器中獲得更好的效能,請改用 $( "your-pure-css-selector" ).has( selector/DOMElement )

範例

將類別「test」新增到所有包含段落的 div。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>has demo</title>
<style>
.test {
border: 3px inset red;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<div><p>Hello in a paragraph</p></div>
<div>Hello again! (with no paragraph)</div>
<script>
$( "div:has(p)" ).addClass( "test" );
</script>
</body>
</html>

示範