Ralph David Abernathy
Ralph David Abernathy

Reputation: 5518

How to check if all elements in an HTMLCollection contain a certain value for a property?

I'm looping over a HTMLCollection like this:

elements.forEach((element) => {

  // If all elements in the collection have a "checked" property of "true"
  if (?) { // Not sure what the check should be here, something like `element.checked.every(Boolean)`?
    // Do stuff
  }
});

Is it possible to write a check to determine if all the children have an property with the same value? Thanks!

Upvotes: 1

Views: 1006

Answers (1)

Spectric
Spectric

Reputation: 31992

You can use spread syntax to convert the NodeList/HTMLCollection to an array, then use Array.every to check whether each item in the array matches the condition in the callback:

const res = [...document.querySelectorAll('input')].every(e => e.checked)
console.log('All checkboxes checked?', res)
<input type="checkbox" checked>
<input type="checkbox" checked>
<input type="checkbox" checked>

Upvotes: 2

Related Questions