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 >
Title
</h1>
<h2 >
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.
CodePudding user response:
Because HTMLCollection
s aren't Array
s. (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>
CodePudding user response:
Rather than using getElementsByClassName
, try querySelectorAll
const test = document.querySelectorAll('.test');
test.forEach(item => {
console.log(item);
});
Simple and work like a charm.
CodePudding user response:
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]
.