This is the third day of my participation in the August More Text Challenge
preface
When looking at the section on obtaining and manipulating DOM nodes, it is mentioned that the types returned by retrieving dom conform to the properties of class arrays, but they are not arrays and cannot use array methods. For example, filter, map, etc., but I saw forEach used in the demo. why? Isn’t forEach also an array method? Write code with some doubt and try it out and look at some articles. Make the following conclusion
The phenomenon of the results
- GetElementByName // Returns the type: NodeList
- GetElementByTagName // The type returned: HTMLCollection
- GetElementByClassName // The type returned: HTMLCollection
- QuerySelectorAll // Return type: NodeList
Note: Class arrays are not a type and should not be confused
<ul>
<li>I'm listing 1</li>
<li>I'm listing 2</li>
<li>I'm listing 3</li>
<li>I'm listing 4</li>
</ul>
<button class="change">Change!</button>
<script>
var lis = document.getElementsByTagName('li');
var btn = document.querySelector('.change');
btn.addEventListener('click'.function() {
lis.forEach(function(li, index) {
li.innerText = index;
});
});
</script>
Copy the code
var lis = document.querySelectorAll('li'); / / is not an error
Copy the code
Therefore, NodeList has forEach methods. HTMLCollection does not have forEach methods. Does NodeList have map and filter methods?
<ul>
<li>I'm listing 1</li>
<li>I'm listing 2</li>
<li>I'm listing 3</li>
<li>I'm listing 4</li>
</ul>
<button class="change">Change!</button>
<script>
var lis = document.querySelectorAll('li');
var btn = document.querySelector('.change');
btn.addEventListener('click'.function() {
lis.map(function(li, index) {
li.innerText = index;
});
});
</script>
Copy the code
Error: nodeList only has forEach, no map, filter, etc
conclusion
There are no methods such as map/filter to obtain the result object returned by DOM nodes, but there are forEach methods when the return type is NodeList. So whether or not a class array has a forEach method depends on the type of object returned. A class array is not a type, it is just a concept.