चर childrenएक NodeListउदाहरण है और NodeListएस सच नहीं हैं Arrayऔर इसलिए वे forEachविधि को विरासत में नहीं लेते हैं ।
इसके अलावा कुछ ब्राउज़र वास्तव में इसका समर्थन करते हैं nodeList.forEach
ES5
आप उपयोग कर सकते हैं sliceसे Arrayकन्वर्ट करने के लिए NodeListएक उचित में Array।
var array = Array.prototype.slice.call(children);
आप इसे केवल संदर्भ के रूप में callलागू करने forEachऔर पास करने के लिए भी उपयोग कर सकते हैं NodeList।
[].forEach.call(children, function(child) {});
ES6
आप fromअपने NodeListको एक में बदलने के लिए विधि का उपयोग कर सकते हैं Array।
var array = Array.from(children);
या आप इस तरह फैल सिंटैक्स का... उपयोग भी कर सकते हैं
let array = [ ...children ];
एक हैक जिसका उपयोग किया जा सकता है NodeList.prototype.forEach = Array.prototype.forEachऔर आप हर बार उन्हें बदलने के लिए बिना forEachकिसी के साथ उपयोग कर सकते हैं NodeList।
NodeList.prototype.forEach = Array.prototype.forEach
var children = element.childNodes;
children.forEach(function(item){
console.log(item);
});
NodeLists, Arrays में एक व्यापक गोता देखें , NodeLists परिवर्तित करना और एक अच्छी व्याख्या और इसे करने के अन्य तरीकों के लिए DOM को समझना ।