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.

4

3 Answers 3

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> 
Sign up to request clarification or add additional context in comments.

Comments

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].

Comments

1

Rather than using getElementsByClassName, try querySelectorAll

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

Simple and work like a charm.

1 Comment

A NodeList (as returned by querySelectorAll) isn't an Array either, though. It does have forEach, but not e.g. .map.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.