5

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?

2
  • [...arrayLike].forEach() or Array.from(arrayLike) Commented Apr 8, 2019 at 8:52
  • Another option is for...of Commented Apr 8, 2019 at 8:54

3 Answers 3

4

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>

Sign up to request clarification or add additional context in comments.

5 Comments

That's only supported in ES6 (2015), which I think is kinda new? I did think that it's so much cleaner, but am worried about its support.
Unless you plan to support <=IE11, looks like you're covered without a polyfill: link
you take arrow functions and let. it is supported in more or less any browser, without IE.
I'm not planning to support below IE11, if at all xD Thank you for the answer.
Oh just found out that the things I've used are from ES6. I was worried for nothing.
1

You can also use spread syntax

[...document.getElementsByClassName('dummy')].forEach((e) => {
  e.classList.add('test')
});
.test {
  color: green;
}
<div class="dummy">Test1</div>
<div class="dummy">Test2</div>

Comments

0

Use Array.from, slice or ... (spreading):

var divs = [...document.getElementsByClassName('dummy')]
divs.forEach(d => console.log(d));
var divs2 = Array.from(document.getElementsByClassName('dummy'));
divs2.forEach(d => console.log(d));
var divs3 = Array.from(document.getElementsByClassName('dummy'));
divs3.forEach(d => console.log(d));
<div class="dummy">Test1</div>
<div class="dummy">Test2</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.