admin管理员组文章数量:1327688
I created a function within getElementsByClassName that tests the current node to check if it matches the className, then recursively tests the childNodes of the current node.
To me, this logically make sense, but I'm not sure why the results don't produce identical results as getElementsByClassName. I tried implementing a for loop that checks every node in the current level, but that doesn't seem to be working either. What do I need to adjust in the first if statement to get this code working?
function getElementsByClassName (className) {
var nodeList = [];
function test(node) {
if (node.classList === className) {
nodeList.push(node.classList[count]);
}
for (var index = 0; index < node.childNodes.length; index++) {
test(node.childNodes[index]);
}
}
test(document.body)
return nodeList;
};
I created a function within getElementsByClassName that tests the current node to check if it matches the className, then recursively tests the childNodes of the current node.
To me, this logically make sense, but I'm not sure why the results don't produce identical results as getElementsByClassName. I tried implementing a for loop that checks every node in the current level, but that doesn't seem to be working either. What do I need to adjust in the first if statement to get this code working?
function getElementsByClassName (className) {
var nodeList = [];
function test(node) {
if (node.classList === className) {
nodeList.push(node.classList[count]);
}
for (var index = 0; index < node.childNodes.length; index++) {
test(node.childNodes[index]);
}
}
test(document.body)
return nodeList;
};
Share
Improve this question
asked Mar 12, 2015 at 15:33
My NameMy Name
1552 silver badges15 bronze badges
3 Answers
Reset to default 3You are making some small when checking the className.
if (node.classList && node.classList.contains(className)) {
nodeList.push(node);
}
http://jsfiddle/us5xjv66/8/
Working solution using underscore.js:
function getElementsByClassName(className) {
var nodeList = [];
function test(node) {
if (_(node.classList).contains(className)) {
nodeList.push(node);
}
_(node.childNodes).forEach(function(child) {
test(child);
});
}
test(document.body);
return nodeList;
}
I think this is what you are trying to achieve:
if (node.className === className) { // if classname matches, add node to list
nodeList.push(node);
}
Or better yet, to handle multiple classnames:
if(node.classList){
if (node.classList.contains(className)) {
nodeList.push(node);
}
}
本文标签: javascriptImplementing getElementsByClassName using RecursionStack Overflow
版权声明:本文标题:javascript - Implementing getElementsByClassName using Recursion - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742217431a2434827.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论