我正在尝试从头开始编写 getElementByClassName,但我不确定何时返回递归。这就是我想到的:
const getElementsByClassName = (nameOfClass, parent) => {
const result = []
for(let el of parent) {
// console.log(el.children)
if(el.firstElementChild != null) {
// do it again on node deeper
getElementsByClassName(nameOfClass, el.children)
}
if(el.className === nameOfClass) {
result.push(el)
}
}
// when do I want to return result?
console.log(result)
return result
};
问题是我每个子节点都有一个数组,而不是同一数组结果中的所有内容。我该如何解决这个问题?
最佳答案
所以你试图通过递归函数遍历 DOM 树!?
当然,每个 child 都有自己的 child 数组。否则它就不是一棵树了。
当您想要返回所有匹配元素的数组时,您必须将结果与递归调用连接起来。
这可行:
const getElementsByClassName = (nameOfClass, parent) => {
const result = []
if (parent.className === nameOfClass) {
result.push(parent);
}
for(let el of parent.children) {
result = result.concat(getElementByClassName(nameOfClass, el));
}
return result
};
此实现只能用于教育目的,因为它具有很大的存储复杂性。
关于javascript - 从头开始编写 getElementsByName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58973674/