0

I was learning about DOM manipulation and have an HTML document.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 class="test">
        Title
    </h1>
    <h2 class="test">
        Here is the list of all the programming languages:
    </h2>
    <ul>
        <li>JavaScript</li>
        <li>Python</li>
        <li>Go</li>
    </ul>
    <script>
        const test = document.getElementsByClassName('test');
        test.forEach(item => {
            console.log(item);
        });
    </script>
</body>
</html>

I have tried accessing the html elements using forEach method but it gives error saying that test.forEach is not a function.

suyashpatil
  • 236
  • 3
  • 11
  • 2
    Does this answer your question? [Most efficient way to convert an HTMLCollection to an Array](https://stackoverflow.com/questions/222841/most-efficient-way-to-convert-an-htmlcollection-to-an-array) – Julia Jan 12 '23 at 09:51
  • 3
    FYI: refer to [documentation for HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) to see what methods are/are not available – Jaromanda X Jan 12 '23 at 09:54
  • 1
    Alternative duplicate: [Iterating over result of getElementsByClassName using Array.forEach](https://stackoverflow.com/questions/3871547/iterating-over-result-of-getelementsbyclassname-using-array-foreach) – Ivar Jan 12 '23 at 09:57
  • This is kinda weird question, like "why a stone can't walk" ... Voted to close as "_this one was resolved in a way less likely to help future readers_". – Teemu Jan 12 '23 at 10:07

3 Answers3

7

Because HTMLCollections aren't Arrays. (For one, as the docs say, a HTMLCollection is live and can change when the document changes; an array can't.)

You can use Array.from(test) or [...test] spreading to make an Array of something that has a .length and supports item access (which HTMLCollection does).

IOW,

<script>
const test = document.getElementsByClassName('test');
[...test].forEach(item => {
  console.log(item);
});
</script>
AKX
  • 152,115
  • 15
  • 115
  • 172
1

Rather than using getElementsByClassName, try querySelectorAll

const test = document.querySelectorAll('.test');
test.forEach(item => {
    console.log(item);
});

Simple and work like a charm.

  • 3
    A `NodeList` (as returned by `querySelectorAll`) isn't an Array either, though. It _does_ have `forEach`, but not e.g. `.map`. – AKX Jan 12 '23 at 10:04
1

HTMLCollection is not an Array but an object. So you can use for loop or you can convert it into an array by doing [...test].

CodeGuru
  • 34
  • 3