Home >Web Front-end >JS Tutorial >Why Doesn't `getElementsByClassName` Return an Array in JavaScript?

Why Doesn't `getElementsByClassName` Return an Array in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 12:23:15719browse

Why Doesn't `getElementsByClassName` Return an Array in JavaScript?

getElementsByClassName Returns an HTMLCollection, Not an Array

In JavaScript, the document.getElementsByClassName method returns a collection of DOM elements that match the specified class name. However, this collection is not an array, but an HTMLCollection.

In modern browsers (Firefox 3 and later), the Array.forEach method can be used with an HTMLCollection by setting the this value of the forEach function to the HTMLCollection. Here's how to do it:

var els = document.getElementsByClassName("myclass");

Array.prototype.forEach.call(els, function(el) {
  // Do something with the element
});

// Or, in ES6+
[].forEach.call(els, (el) => {
  // Do something with the element
});

A more modern approach using ES6 is to use Array.from to convert the HTMLCollection into an actual array:

Array.from(els).forEach((el) => {
  // Do something with the element
});

By setting the this value or using Array.from, you can iterate over the HTMLCollection using the forEach method as if it were an array. Note that older browsers like Internet Explorer 8 and below do not support this approach, and will return a NodeList instead of an HTMLCollection.

The above is the detailed content of Why Doesn't `getElementsByClassName` Return an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn