17

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']");
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
mark uy
  • 521
  • 1
  • 6
  • 17

2 Answers2

31

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.

Rafael
  • 7,605
  • 13
  • 31
  • 46
10

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>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320