Chrismar
Chrismar

Reputation: 93

Javascript forEach method is working for NodeList

I am learning about DOM manipulation and I noticed that when I create a NodeList by using document.querySelectorAll that I am able to use a ForEach Loop. That should not be possible. Why does it work? It is only suppose to work on Arrays.

var items = document.querySelectorAll("li");
console.log(items);

items.forEach(function(item){
    item.addEventListener("click", function(){
        item.classList.toggle("finished");
    });
    item.addEventListener("mouseover", function(){
        item.classList.add("over");
    }, false);
    item.addEventListener("mouseleave", function(){
        item.classList.remove("over");
    });
})

Upvotes: 3

Views: 137

Answers (1)

Bamieh
Bamieh

Reputation: 10906

This depends on the browser, its supported in chrome but not in other browsers. The NodeList has forEach in its prototype in chrome, it does not in other browsers.

// to check for forEach support
if(NodeList.prototype.forEach) /*...*/

to loop over the NodeList in all browsers:

for (var i = 0, l=myNodeList.length; i < l; ++i) {
  var item = myNodeList[i];
}

or you can simply convert it into an array:

var div_list = document.querySelectorAll('div'); // returns NodeList
var div_array = Array.prototype.slice.call(div_list); // converts NodeList to Array

you can read more details here: https://developer.mozilla.org/en/docs/Web/API/NodeList

Upvotes: 3

Related Questions