During the interview, you need to convert the array-like object into an array and record the method.
Often when operating dom, what is obtained is an array-like object, so the method of the array cannot be directly used.
- ES6 syntax Array.from()
let arr=Array.from(list);
- Use the method Array.prototype.slice.call on the prototype chain
let p=document.getElementsByTagName('p');
p.forEach(item=>{
item.addEventListener('click',()=>{
console.log(item.innerHtml)
})
})
Traversing with a class array is an error, so it needs to be converted to a real array
let p=document.getElementsByTagName('p');
p=Array.prototype.slice.call(p);
p.forEach(item=>{
item.addEventListener('click',()=>{
console.log(item)
})
})
3. Use the […] deconstruction method to convert it into an array
let p=document.getElementsByTagName('p');
p=[...p]
p.forEach(item=>{
item.addEventListener('click',()=>{
console.log(item)
})
})```