如何检查 HTMLCollection 中的所有元素是否都包含 属性 的特定值?
How to check if all elements in an HTMLCollection contain a certain value for a property?
我正在像这样遍历 HTMLCollection:
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
}
});
是否可以编写一个检查来确定是否所有 children 都具有相同值的 属性?谢谢!
您可以使用spread syntax to convert the NodeList/HTMLCollection to an array, then use Array.every
检查数组中的每一项是否匹配回调中的条件:
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>
我正在像这样遍历 HTMLCollection:
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
}
});
是否可以编写一个检查来确定是否所有 children 都具有相同值的 属性?谢谢!
您可以使用spread syntax to convert the NodeList/HTMLCollection to an array, then use Array.every
检查数组中的每一项是否匹配回调中的条件:
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>