我正在尝试重新实现getElementsByClassName函数。作为我的函数的一部分,我想以一个元素的子节点递归调用我的函数w /它自己的子节点。
然而,尽管我记录了控制台日志记录,我正在将一个带有子节点的值传递给函数,但是当我在递归调用它之后立即记录该元素时,它说我的元素是未定义的,因此当我要求时它会失败得到它的子节点。
这是我的代码。
var getElementsByClassName = function(className) {
var results = [];
function inner(element) {
console.log(element); //eventually says undefined unexpectedly
var children = element.childNodes;
console.log(Array.isArray(children));
for (var i = 0; i < children.length; i++){
console.log("the class list is: ", children[i].classList);
if (children[i].classList !== undefined){
if (children[i].classList.value === className) {
results.push(children[i]);
}
}
console.log("the child nodes are: ", children[i].childNodes);
if (children[i].childNodes.length !== 0){
console.log("the one that's supposed to have child nodes is", children[i]); //lists an element w/ child nodes
return inner(document[children[i]]);
}
}
return results;
}
return inner(document.body);
};
console.log(getElementsByClassName("targetClassName"));
console.log(document.getElementsByClassName("targetClassName"))
答案 0 :(得分:0)
您将文档称为具有元素div属性的对象,但它不能具有此类属性
return inner(document[children[i]]);
应该是
return inner(children[i]);