:has

:has() CSS 伪类代表一个元素,其给定的选择器参数(相对于该元素的 :scope)至少匹配一个元素。

:has() 伪类接受一个选择器组作为参数。在当前规范中 :has 并未列为实时选择器配置的一部分,意味着其不能用于样式表中,只能用于如 document.querySelector() 的函数中。

/* 选择任何直接包含 <img> 子元素的 <a>  */
/* 注意,目前还没有任何浏览器支持此方法 */
/* 此伪类也未计划投入样式表中使用 */
var test = document.querySelector('a:has(> img)');

语法

:has( <relative-selector-list> )

where
<relative-selector-list> = <relative-selector>#

where
<relative-selector> = <combinator>? <complex-selector>

where
<combinator> = '>' | '+' | '~' | [ '||' ]
<complex-selector> = <compound-selector> [ <combinator>? <compound-selector> ]*

where
<compound-selector> = [ <type-selector>? <subclass-selector>* [ <pseudo-element-selector> <pseudo-class-selector>* ]* ]!

where
<type-selector> = <wq-name> | <ns-prefix>? '*'
<subclass-selector> = <id-selector> | <class-selector> | <attribute-selector> | <pseudo-class-selector>
<pseudo-element-selector> = ':' <pseudo-class-selector>
<pseudo-class-selector> = ':' <ident-token> | ':' <function-token> <any-value> ')'

where
<wq-name> = <ns-prefix>? <ident-token>
<ns-prefix> = [ <ident-token> | '*' ]? |
<id-selector> = <hash-token>
<class-selector> = '.' <ident-token>
<attribute-selector> = '[' <wq-name> ']' | '[' <wq-name> <attr-matcher> [ <string-token> | <ident-token> ] <attr-modifier>? ']'

where
<attr-matcher> = [ '~' | | | '^' | '$' | '*' ]? '='
<attr-modifier> = i | s

示例

下面的选择器只会匹配直接包含 <img> 子元素的 <a> 元素:

a:has(> img)

下面的选择器只会匹配其后紧跟着 <p> 元素的 <h1> 元素:

h1:has(+ p)

规范

规范 状态 注释
Selectors Level 4
:has()
Working Draft Initial definition

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
:has()
Experimental
Chrome No support No
Notes
No support No
Notes
Notes See bug 669058
Edge No support NoFirefox No support No
Notes
No support No
Notes
Notes See bug 418039
IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoFirefox Android No support No
Notes
No support No
Notes
Notes See bug 418039
Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support No

Legend

No support  
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
See implementation notes.
See implementation notes.