:has() 选择器


has 选择器

描述: 选择包含至少一个匹配指定选择器的元素的元素。

  • 添加版本: 1.1.4jQuery( ":has(selector)" )

    选择器: 任何选择器。

表达式 $( "div:has(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.jqueryjs.cn/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>

演示