我必须从头开始编写 .getElementByClassName
。这是我到目前为止的代码。
var getElementsByClassName = function(className){
let result = [];
let bod = document.body;
for (let prop in bod) {
if (bod[prop].classList && bod[prop].classList.contains(className)) {
result.push(bod[prop]);
}
let child = bod[prop].childNodes;
for(let elem in child) {
if (child[elem].classList.contains(className)) {
result.push(child[elem]);
}
}
}
return result;
};
我无法访问 document.body
。是我的语法错误还是 for 循环不合适?
最佳答案
prop in bod
甚至会返回它的方法/属性,它们没有 classList
,只有 Node
有。
因此,您需要的是它的子节点,也就是 document.body.childNodes
。像这样的东西:
for (let i = 0; i<bod.childNodes.length; i++) {
let thisNode = bod.childNodes[i];
if (thisNode.classList) {
// check if it has your class
}
if (thisNode.childNodes.length) {
// go deeper in the node, recursively
}
}
而且一个循环是不够的,你不知道你需要多少个,因为每个节点可以有任意数量的子节点,所以你需要递归。
关于javascript - 如何遍历 document.body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55533496/