Traversing the Results from query SelectorAll() with forEach() and call()
Problem
You want to use forEach() on the nodeList returned from a call to querySelector All().
Solution
You can coerce forEach() into working with a NodeList (the collection returned by
querySelectorAll()) using the following:
// use querySelector to find all second table cells var cells = document.querySelectorAll("td + td"); [].forEach.call(cells,function(cell) { sum+=parseFloat(cell.firstChild.data); });
EXPLAIN
The forEach() is an Array method, and the results of querySelectorAll() is a NodeList, which is a different type of object than an Array. In the solution, to get forEach() to work with the NodeList, we’re calling the method on an empty array, and then using call() on the object to emulate the effect of an Array method on the NodeList, as if it were an actual array.
Simple, but there are drawbacks. Unless you convert the NodeList into an Array, the coercion is a one-shot that has to be repeated if you need to use the same functionality again. In addition, later in the code you may automatically try another Array method on the NodeList, only to have it fail because you didn’t use coercion
No comments:
Post a Comment