AsksAnyway
AsksAnyway

Reputation: 930

How should I iterate through the results of multiple getElementsByClassName() calls in the same loop?

I'd like to do this:

a1 = document.getElementsByClassName('classA');
a2 = document.getElementsByClassName('classB');
a3 = a1.concat(a2);

for (var i=0; i<a3.length; ++i) {

}

i.e. get all the elements of classA, all the elements of classB and then combine them in a way that allows me to iterate through all of them. It doesn't work because getElementsByClassName doesn't return a standard array.

This works but there has to be a more sensible way:

var els = [];
var e1 = document.getElementsByClassName('classA');
var e2 = document.getElementsByClassName('classB');
[].forEach.call(e1, function(el) { els.push(el); });
[].forEach.call(e2, function(el) { els.push(el); });

Upvotes: 0

Views: 1744

Answers (2)

Guffa
Guffa

Reputation: 700222

The getElementsByClassName method returns an HTMLCollection rather than an array. It's an array-like object, but you can't use all array methods on it.

Turn the collections into arrays using the slice method, then you can concatenate them:

var a3 = Array.prototype.slice.call(a1).concat(Array.prototype.slice.call(a2));

Note: This requires IE9 or later.

Upvotes: 1

Walter Schwarz
Walter Schwarz

Reputation: 153

In modern browsers you can use:

var a = document.querySelectorAll('.classA, .classB');

This finds all elements with 'classA' or 'classB'. You can find more info and a browser compatibility table here.

Upvotes: 5

Related Questions