0

How can I select an attribute without a value?

Can I avoid using data-number="value" to setting or get the attribute in JavaScript?

const numberButtons = document.querySelectorAll('[data-number]')
console.log(numberButtons.length)
<button data-number>1</button>
<button data-number>2</button>
<button data-number>3</button>

I want to get the NodeList. This way the numberButtons return a empty NodeList.

Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102
Wilker
  • 17
  • 2

1 Answers1

0

How can I select an attribute without a value?

The method you are using works:

document.querySelectorAll('[data-number]')

Can I avoid using data-number="value" to setting or get the attribute in JavaScript?

Yes. To access the data- attribute's value from the node, use dataset.

I want to get the NodeList. This way the numberButtons return a empty NodeList.

This will return your NodeList:

console.log(numberButtons)

To expand on how data- attributes are read:

const numberButtons = document.querySelectorAll('[data-number]')
console.log(numberButtons.length)
console.log(
  [...numberButtons].map(i => i.dataset.number)
)
<button data-number="1">1</button>
<button data-number="2">2</button>
<button data-number="3">3</button>

Notice how dataset contains an object, where any attributes line up with a camelCased version of whatever you called the attribute, so data-number becomes dataset.number, and data-super-number would become dataset.superNumber.

Another thing to keep in mind is when your code is executing, to avoid your JavaScript executing before the DOM is constructed, make sure to wrap your code in a DOMContentLoaded listener, like so:

document.addEventListener('DOMContentLoaded', () => {
    const numberButtons = document.querySelectorAll('[data-number]')
    console.log(numberButtons.length)
    console.log(
      [...numberButtons].map(i => i.dataset.number)
    )
})
ryanpcmcquen
  • 5,446
  • 3
  • 20
  • 34