querySelect 由 css 类的部分

js是否可以选择不包含类特定部分的特定元素,例如:


// This line seems to be an invalid query parameter, so I am curious if it's actually feasible to achieve that?

const queryResult = document.querySelectorAll(`ul:not('.*__list')`);

const queryResult = document.querySelectorAll(`ul`);

console.log(queryResult)

<div>

  <ul>

    <li>item</li>

    <li>item</li>

    <li>item</li>

    <li>item</li>

    <button>button</button>

  </ul>

  <ul class="abstractPrefix__list">

    <li>

      <button class="abstractPrefix__button">button</button>

    </li>

  </ul>

</div>


PIPIONE
浏览 130回答 2
2回答

月关宝盒

如果您确定class属性总是以 结尾__list,那么您可以使用属性选择器[class$='__list']。const queryResult = document.querySelectorAll(`ul:not([class$='__list'])`);console.log(queryResult)<div>&nbsp; <ul>&nbsp; &nbsp; <li>item</li>&nbsp; &nbsp; <li>item</li>&nbsp; &nbsp; <li>item</li>&nbsp; &nbsp; <li>item</li>&nbsp; &nbsp; <button>button</button>&nbsp; </ul>&nbsp; <ul class="abstractPrefix__list">&nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; <button class="abstractPrefix__button">button</button>&nbsp; &nbsp; </li>&nbsp; </ul></div>但是,如果您的类列表如下所示,此选择器将失败class="abstractPrefix__list my_random_class": ,因为它将不再匹配上述 CSS 属性选择器。在这种情况下,您将需要一个基于 JS 的解决方案:const queryResult = Array.from(document.querySelectorAll('ul')).filter(el => {&nbsp; const classes = Array.from(el.classList);&nbsp; for (let cl of classes) {&nbsp; &nbsp; if (cl.match(/__list$/gi)) {&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; continue;&nbsp; }&nbsp;&nbsp;&nbsp; return true;});console.log(queryResult)<div>&nbsp; <ul>&nbsp; &nbsp; <li>item</li>&nbsp; &nbsp; <li>item</li>&nbsp; &nbsp; <li>item</li>&nbsp; &nbsp; <li>item</li>&nbsp; &nbsp; <button>button</button>&nbsp; </ul>&nbsp; <ul class="abstractPrefix__list my_random_class">&nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; <button class="abstractPrefix__button">button</button>&nbsp; &nbsp; </li>&nbsp; </ul></div>

小怪兽爱吃肉

文档:https://drafts.csswg.org/selectors/#overview在此页面内,阅读以下内容:E[foo*="bar"] 一个 E 元素,其 foo 属性值包含子字符串 barE:not(s1, s2, …) 不匹配复合选择器 s1 或复合选择器 s2 的 E 元素所以你必须使用类似这样的东西:document.querySelectorAll('ul:not([class*="__list"])')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript