As I've answered questions on this website, I've began to use .forEach()
a lot more. I've also started using document.getElementsByClassName()
, or document.querySelectorAll()
a lot more.
I've recently noticed that sometimes, .forEach()
works, and sometimes it doesn't. After a bit of research, I found out that you can't .forEach()
through a NodeList
. Then I went to this answer and found out that you can .forEach()
on a NodeList.
Note: I've also added 2 snippets below in which .forEach()
works, and doesn't work. It seems to work for document.querySelectorAll()
but not document.getElementsByClassName()
, but why? Don't they both return a NodeList
?
TL;DR: Why can I .forEach()
on some NodeLists
, but not all?
.forEach()
works on this snippet.
let text = document.querySelectorAll(".text");
console.log(typeof text);
text.forEach(e => {
console.log(e);
});
<div class="text">Text</div>
<div class="text">Text</div>
<div class="text">Text</div>
<div class="text">Text</div>
.forEach()
doesn't work on this snippet.
let text = document.getElementsByClassName("text");
console.log(typeof text);
text.forEach(e => {
console.log(e);
});
<div class="text">Text</div>
<div class="text">Text</div>
<div class="text">Text</div>
<div class="text">Text</div>