Last updated on March 27, 2020
In this blog post, you’ll learn the real practical issue Why Iterating on HTML Elements not worked with JavaScript Array Operators.
Introduction
We have faced this situation many times, then later realized that Using Javascript array operators
on HTML elements array doesn’t work.
Why Iterating on HTML Elements not worked with JavaScript Array operators
For example, let’s we have the below template mark-up,
<div name="one"></div>
<div name="one"></div>
<div name="one"></div>
<div name="one"></div>
To manipulate the above elements we will query the DOM elements like below,
const elements= document.querySelectorAll('.one');
elements.forEach(function (item){ });
Here, the `elements` variable is an Array-like
object but not an array.
To fix this first, we should cast the array-like object to an array object.
const elements= document.querySelectorAll('.one');
if(elements) { Array.from(elements).forEach(function (item){ });
}
Array.from(<HTML Elements[]>)
would solve the problem.