15

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
  • 665,005
  • 155
  • 1,345
  • 1,328
mark uy
  • 501
  • 1
  • 5
  • 16

2 Answers2

27

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,324
  • 13
  • 32
  • 45
9

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
  • 313,535
  • 40
  • 245
  • 254