JS — [].forEach.call(NodeList) hack — Array-like object
2 min readAug 23, 2018
A node list is not an array!
A node list may look like an array, but it is not.
You can loop through the node list and refer to its nodes like an array.
https://medium.com/@kes3583/select-dom-and-add-style-queryselector-and-queryselectorall-cc2fbd4dbaa1
However, you cannot use Array Methods, like valueOf(), push(), pop(), or join() on a node list.
letterList = slide.querySelectorAll('.el');
var letters = [];
for (var i = letterList.length; i--;) { // reverse
letters.push(letterList[i])
}//orthis.slides = [];
var self = this;[].slice.call(this.el.querySelectorAll('.slide')).forEach(function(slide) {self.slides.push(new Slide(slide)); //each .element and TextFx in Array});
- added 03–09 -Array-like object
- I found this [Array.from] while i exam other’s code
- array.from — return an array objects
- - array-like objects (objects with a
length
property and indexed elements) or - iterable objects (objects where you can get its elements, such as
Map
andSet
).
const DOM = {};
DOM.contentElems = Array.from(document.querySelectorAll('.content-wrap'));
DOM.contentLinks = Array.from(document.querySelectorAll('.content__link'));
--------------<div class="text">
<span>e</span>
<span>u</span>
<span>n</span>
<span>s</span></div>
<script>var myArr = Array.from("ABCDEFG");
var textWrapper = document.querySelector('.text');
var _textAll = textWrapper.querySelectorAll('span');
var _text = [].slice.call(textWrapper.querySelectorAll('span'));var _textArr = Array.from(textWrapper.querySelectorAll('span'));console.log('text-all',_textAll)
_text[0].style.color = 'green';console.log('text-slice.call',_text)
_text[1].style.color = 'red';console.log('text-array.from',_textArr)
_textArr[2].style.color = 'blue';document.getElementById("demo").innerHTML = myArr;</script>//
text-all NodeList(4) [span, span, span, span] // this is only nodeList
text-slice.call (4) [span, span, span, span]
text-array.from (4) [span, span, span, span]
#array.forEach(function(currentValue, index, arr), thisValue)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
#reference
- in reverse
https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/#problem-10-not-cross-browser