We can achieve iteration on array-like objects using both of the following methods:
let arrayLike = document.getElementsByClassName('dummy');
[].forEach.call(arrayLike, (e) => {
console.log(e);
});
<div class = "dummy">Test1</div>
<div class = "dummy">Test2</div>
Or using slice
to convert array-like objects to array first:
let arrayLike = document.getElementsByClassName('dummy');
Array.prototype.slice.call(arrayLike).forEach((e) => {
console.log(e);
});
<div class = "dummy">Test1</div>
<div class = "dummy">Test2</div>
Which one is more preferrable and why in the case where I need not the converted array-like object? The first one feels a little 'hacky' but the second one feels more readable. Or are both just the same, meaning both will do just fine?
You could take Array.from
and convert the array like object to a real array. Then iterate with some of the array methods.
let array = Array.from(document.getElementsByClassName('dummy'));
array.forEach((e) => {
console.log(e);
});
<div class = "dummy">Test1</div>
<div class = "dummy">Test2</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With