Given the following test environment …
const nodeList = document.querySelectorAll('p');
const testArray = Array.from(nodeList);
testArray.every(function (elmNode) {
if (elmNode.classList.contains('ipsum')) {
console.log(
'All element nodes do feature the `ipsum` css-class name.'
);
}
});
.lorem {
font-family: courier new, courier;
}
<p class="lorem ipsum">Lorem ipsum</p>
<p class="lorem dolor sit">dolor sit</p>
<p class="lorem amet">amet.</p>
… the above implementation does not log the correct result.
How can one detect whether each element of a list of element-nodes does feature a specific css-class name?
And as for the above example code, how would one execute an additional function in case the condition (every element node features a specific class-name) is met?
2
Answers
The callback function used in the .every(…) prototype function should return a boolean value. If you want to perform an operation based on whether all elements contain a value or meet a certain class condition, you should act according to the result of the .every(…) function
One firstly should consult a reliable documentation/reference like MDN on the
every
array method.Secondly, one might write a test case, boiled down to the most necessary scenario/environment, not only for a well asked question on Stackoverflow, but utmost for ones own (debugging) sake.
As already stated, the
every
method expects a callback function which has to return a boolean (or a truthy/falsy) value.The OP’s edited example code then changes to …
Following the OP’s comment …
… the example code easily changes to …