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.
With a querySelector statement, you can select an element based on a CSS selector. This means you can select elements by ID, class, or any other type of selector.
querySelector() to find elements with a specific class name that are within a div with a specific ID.
Differences: As seen above, querySelector() methodcan only be used to access a single element while querySelectorAll() method can be used to access all elements which match with a specified CSS selector. To return all matches, querySelectorAll has to be used, while to return a single match, querySelector is used.
getElementById is better supported than querySelector . querySelector is better supported than getElementsByClassName but querySelector gives you a static node list while getElementsByClassName gives you a live node list. You need to pick the appropriate tool for any given task.
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
.
I guess you are looking for :not()
and "starts with" selectors:
document.querySelectorAll('ul.numberList li:not([id^=test])')
(Or replace ^
with *
in case you want "includes", not "starts with")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With