Javascript querySelectorAll data attribute value not equal to

Viewed 16225

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']");
2 Answers

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>

Related