Contact!

HTMLCollection forEach loop – Convert object to array: JavaScript

forEach loop JavaScript

Ever had an array-like object that you want to iterate over? These annoying collections, which look like arrays, don’t have access to useful array methods like the ‘forEach‘ loop. They include objects with a length property, such as HTMLCollection, NodeList, argument list and even strings. Today I’m going to show you how to make these objects a little bit more useful, by converting them into JavaScript arrays.

Let’s start with a simple scenario where we have 5 divs. Each div has the same class and we query for a HTMLCollection using ‘getElementsByClassName‘.

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

<script>
    const boxes = document.getElementsByClassName('box');
</script>

Here are 4 ways to convert the returned HTMLCollection to an array.

Convert to array using a spread operator

A spread operator will allow us to expand the values of our array-like object and push them into a new array. This works because the HTMLCollection is iterable. The code looks something like this:

const boxArray = [...document.getElementsByClassName('box')];

Convert to array using Array.from()

Array.from does what it sounds like; it converts array-like objects to actual arrays. This is my preferred method of converting to array because it is semantically very easy to read at a glance. You should note that this method isn’t actually supported by Internet Explorer, but who cares about Internet Explorer now anyway…

const boxes = Array.from(document.getElementsByClassName('box'));

Convert to array using Array.prototype.slice.call()

More widely supported, we can use the Array.prototype.slice.call() (or [].slice.call for short) methods for converting. Basically we are using the array method ‘slice‘ (which returns a copy of an array) on an array-like object with a ‘call’ method, and then saving the copy into a new array object.

var boxes = Array.prototype.slice.call(document.getElementsByClassName('box'));

var boxes = [].slice.call(document.getElementsByClassName('box'));

Convert to array using an iterator loop

Last, but not least, you could solve this problem the good old fashioned way; with a simple iterator loop. From here we could loop our array-like object ‘as-is’ or push each iteration to a new array (in this case ‘boxArray’) for a future use.

const boxes = document.getElementsByClassName('box');
const boxArray = [];

for (let i = 0; i < boxes.length; i++) {
    console.log(boxes[i]);

    // At this point we could also push the elements to an array
    boxArray.push(boxes[i]);
}

  1. Mike says:

    Exactly what I needed.

  2. David says:

    YES I AGREE

  3. Guillaume says:

    Ohhh thank you dude !!! I wanted to style elements by classNames but it doesn’t work with forEarch. I searched documentation everywhere about this.

  4. Tobias says:

    Thanks ever so much – just what I needed!

  5. mwai wachira says:

    I am getting [object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement] as the output to innerHTML I have set. How can I get the actual values between the DIVS.

  6. Ana Maria says:

    Thank you! This article was all I needed!

  7. Drew says:

    I KISS YOU

Join the discussion!

You might like:

Create, register and use shortcodes in WordPress

Create, register and use shortcodes in WordPress

by Gav 18/03/2023

Learn how to create and register your own WordPress shortcodes to add dynamic content to your posts and pages.

How to use guard clauses in JavaScript

How to/why use guard clauses in JavaScript

by Gav 16/03/2023

Learn how to improve code readability and performance by using guard clauses in JavaScript. Discover their benefits and best practices.

Implements and Extends, Object Oriented TypeScript

Implements and Extends, Object Oriented TypeScript

by Gav 15/03/2023

Learn the difference between implements and extends in TypeScript. Use Implements to implement interfaces and types, and extends to inherit from classes.

Reading/Parsing and Writing YAML files in PHP, Symfony

Reading/Parsing and Writing YAML files, PHP Symfony

by Gav 14/03/2023

In this tutorial we will look at using YAML in PHP. Learn about Parsing and Writing YAML files using Symfony's YAML component.

Measuring code execution performance in JavaScript

Measuring code execution performance in JavaScript

by Gav 13/03/2023

Measuring code execution performance is an important way to identify bottlenecks. Use these methods in JavaScript to help optimise your code.

Measuring script/code execution time in PHP using microtime

Measuring script/code execution time in PHP, microtime

by Gav 06/03/2023

Find bottlenecks, optimise and clean your code, and speed up your apps by measuring the execution time of your PHP scripts using microtime.

Regenerate WordPress media image sizes, programmatically

Regenerate WordPress media image sizes, programmatically

by Gav 25/02/2021

Learn how to regenerate and update WordPress media and image sizes both programmatically (without plugin), and also with a handy plugin.

Magic Constants in PHP. What they are and how to use them.

Magic Constants in PHP. What they are and how to use them

by Gav 15/02/2021

Ever seen constants like __DIR__ and __FILE__ being used in PHP? These are 'Magic Constants', and this is how we can use them.

Detecting Keypress JavaScript

Detect single and multiple keypress events: JavaScript

by Gav 16/10/2019

Learn how to use event listeners to detect and handle single and multiple keypress events in JavaScript. Add modifier keys to your application!