My HTML tags have a [data-value]
attribute which can be 0, 1, 2 and so on..
If I want to get the elements whose [data-value]
is not equal to 0, how do I write my query selector?
I tried the following but they don't work:
element.querySelectorAll("not[data-value='0']");
element.querySelectorAll("[data-value!='0']");
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document. Here is the HTML for the examples in this article.
Originally Answered: Why is my querySelectorAll() method not working ? Make sure that the engine is executing the method call after the content, you are interested in, is loaded into the DOM. If you are constructing the query selector dynamically, then make sure it is correct during execution.
To retrieve all copies of a specific element, you can simply pass the name of the element as its argument. You can also select elements by other attributes like target or value : // return all elements with target="_blank" document. querySelectorAll("[target=_blank]"); // return all elements with value="red" document.
querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
To avoid selecting other divs, use div[data-value]:not([data-value="0"])
:
console.log(
document.querySelectorAll('div[data-value]:not([data-value="0"])')
);
<div data-value="-1">0</div>
<div data-value="0">0</div>
<div data-value="1">1</div>
<div data-value="2">2</div>
<div>3</div>
This selects all divs with data-value and its value is NOT 0.
Use the selector string 'div:not([data-value="0"])'
:
document.querySelectorAll('div:not([data-value="0"])')
.forEach(div => console.log(div));
<div data-value="0">0</div>
<div data-value="1">1</div>
<div data-value="2">2</div>
You can't use [attrib!=value]
in vanilla Javascript/CSS, unfortunately, you have to use :not
instead. (though, you can use [attrib!=value]
in jQuery)
To select <div>
s which have additionally have a data-value
attribute, but have one which is not 0
, add [data-value]
after the initial div
in the selector string:
document.querySelectorAll('div[data-value]:not([data-value="0"])')
.forEach(div => console.log(div));
<div data-value="0">0</div>
<div data-value="1">1</div>
<div data-value="2">2</div>
<div>3</div>
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