user6468132 user6468132 - 5 months ago 28
Javascript Question

Using querySelector exclude elements whose id's include a spesific string

I want to get results whose id does not include a string (let's say it's is "test")

<ul class="numberlist">
<li id="test1" style="display:none">
<div></div>
</li>
<li>
<a>one</a>
</li>
<li>
<a>two</a>
</li>
<li>
<a>three</a>
</li>
<li id="test2" style="display:none">
<div></div>
</li>
<li>
<a>four</a>
</li>
<li id="test" style="display:none">
</div></div>
</li>
</ul>


As I said I want to exclude which has id that includes string
test
. How can I achieve it?

I can get the list of
<li>
's by writing

document.querySelectorAll('ul.numberList')


But I want to exclude some of them by their id's.

Answer

You can use attribute contains selector with :not() pseudo-class selector

document.querySelectorAll('ul.numberlist li:not([id*="test"])')

console.log(document.querySelectorAll('ul.numberlist li:not([id*="test"])').length)
<ul class="numberlist">
  <li id="test1" style="display:none">
    <div></div>
  </li>
  <li>
    <a>one</a>
  </li>
  <li>
    <a>two</a>
  </li>
  <li>
    <a>three</a>
  </li>
  <li id="test2" style="display:none">
    <div></div>
  </li>
  <li>
    <a>four</a>
  </li>
  <li id="test" style="display:none">
    <div></div>
  </li>
</ul>


FYI : document.querySelectorAll('ul.numberList') , doesn't get all li element, instead which gets all ul with class numberList. To get all li inside use selector as ul.numberList li. Also in your html class name is numberlist not numberList.