Element.matches选择器限制

时间:2020-04-16 04:52:35

标签: javascript html

我正在尝试将Element.matches与复杂的选择器一起使用,但出现错误:

Uncaught DOMException: Failed to execute 'matches' on 'Element': ':not(.myContainer *)' is not a valid selector.

var myMatchedElement = document.getElementById('iShould');
console.log(myMatchedElement.matches(':not(.myContainer *)'));

var myNotMatchedElement = document.getElementById('iShouldNot');
console.log(myNotMatchedElement.matches(':not(.myContainer *)'));
<div id="app">
  <div id="iShould">I should match the selector</div>
  <div class="myContainer">
    <span id="iShouldNot">I should not</span>
  </div>
</div>

这是选择器的简化版本,但基本上我需要使用“:not(.class childs)”并使用Element.matches。

1 个答案:

答案 0 :(得分:1)

:not()仍仅接受simple selectors.myContainer *complex selector,而不是简单选择器

即使CSS也不接受您的规则。

:not(.myContainer *) {
  color: green;
}
<div id="app">
  <div id="iShould">I should match the selector</div>
  <div class="myContainer">
    <span id="iShouldNot">I should not</span>
  </div>
</div>

请注意,Selectors 4现在扩展了not()函数以接受复杂选择器列表,但是只有Safari才实现了。

相关问题