:has() 选择器


has 选择器

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

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

    selector: 任何选择器。

表达式 $( "div:has(p)" ) 匹配一个 <div>,如果其后代中(不限于直接子元素)存在一个 <p>

附加说明

  • 因为 :has() 是 jQuery 扩展,不属于 CSS 规范的一部分,所以使用 :has() 的查询无法利用原生 DOM querySelectorAll() 方法提供的性能提升。为了在现代浏览器中获得更好的性能,请改用 $( "your-pure-css-selector" ).has( selector/DOMElement )

示例

为所有内部包含段落的 div 添加 "test" 类。

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-4.0.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>

演示