About document.getElementsByTagName in ES5

topic description

the interviewer asked me how to cycle through all div of document.getElementsByTagName ("div") . I said use for loop, and he said no. Excuse me, what"s going on? I"m in a circle now

.

sources of topics and their own ideas

related codes

/ / Please paste the code text below (do not replace the code with pictures)

what result do you expect? What is the error message actually seen?

Mar.28,2021

The

for loop is absolutely possible, and it's probably not what the interviewer expected.

because document.getElementsByTagName ('div') gets a class array object, not a real array,

probably want you to convert the class array object into the array object, and then use the array map forEach and other methods


for loops are OK.

var nodeList = document.getElementsByTagName('div'); 
for (var i = 0; i < nodeList.length; iPP) {
    // code here
    console.log(1);
}

the interviewer may prefer you to answer how this is an array object of the array-like-object class. And then do the cycle.

Plan 1: ES5 Array.prototype.slice.call

var nodeList = document.getElementsByTagName('div'));
var nodeArr = Array.prototype.slice.call(nodeList);
// [].slice.call() 
Array.isArray(nodeArr); // true
nodeArr.forEach(() => {
    console.log(1);
});

Scheme 2: ES6 extension .

// NodeList
var nodeArr = [...document.querySelectorAll('div')];
nodeArr.forEach(() => {
    console.log(1);
});

Plan 3: ES6 Array.from

Array.from(document.querySelectorAll('div')).forEach(() => {
    // code here
    console.log(1);
});

the interviewer should want you to name the three options of switching to an array. I hope it will be helpful to you ~


calls methods such as getElementsByTagName, document.childNodes, and so on, which return NodeList objects that belong to pseudo arrays. Methods such as loops and push under Array cannot be applied. Convert it to an array before processing:

var domNodes = Array.prototype.slice.call(document.getElementsByTagName("div"));
domNodes.forEach(function(){
  //.....
})
The

MDN is also traversed with a for loop. What's wrong with that? MDN

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b36317-2bff9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b36317-2bff9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?