【问题标题】:Element.matches selector limitations [duplicate]Element.matches 选择器限制
【发布时间】:2020-04-16 13:24:52
【问题描述】:

我正在尝试将 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。

【问题讨论】:

  • :not() 只接受简单的选择器,.myContainer * 是一个复杂的选择器。甚至 CSS 也不会接受你的规则。
  • 是的,我刚刚在另一个答案中发现...我很困惑,因为我在 JQuery 中使用了那个选择器
  • 是的 jQuery :not 不是 w3c 的(它是以前制作的,并且接受更复杂的选择器)

标签: javascript html


【解决方案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 实现了它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多