चर 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 को समझना ।