Hey,
I am working on reimplementing document.getElementsByClassName using vanilla javascript. My code doesn’t seem to be working, and I don’t know for the life of me why. Any help would be appreciated.
Here is the code:
var getElementsByClassName = function(className) {
function domCrawler(node) {
var results = [];
// check if the node has any classes at all, then if it has the target class
if (node.classList && node.classList.contains(className)) {
//child has target class, add it to results
results.push(node);
}
// check if the node has children nodes
if (node.hasChildNodes()) {
// it does, so store them in a variable to iterate through
var children = node.childNodes;
// iterate through the node's children to check if they have the target class
for (var i = 0; i < children.length; i++) {
// send each child back through the domCrawler
// the results of this function call stack will be in an array different from the original results array
// we can combine the different results arrays using concat()
results = results.concat(domCrawler(children[i]));
}
}
return results;
}
domCrawler(document.body);
};
You’re not returning anything from your getElementsByClassName
function.
From your domCrawler
, yes, but not from your main function.
I reformatted this very slightly to use a closure so that you would not be re-creating the domCrawler
function on every invocation of getElementsByClassName
, but it is almost completely the same as yours, and it works just fine here:
const elementsByClassName = (function(){
function domCrawler(node, className) {
var results = [];
// check if the node has any classes at all, then if it has the target class
if (node.classList && node.classList.contains(className)) {
//child has target class, add it to results
results.push(node);
}
//debugger;
// check if the node has children nodes
if (node.hasChildNodes()) {
// it does, so store them in a variable to iterate through
var children = node.childNodes;
// iterate through the node's children to check if they have the target class
for (var i = 0; i < children.length; i++) {
// send each child back through the domCrawler
// the results of this function call stack will be in an array different from the original results array
// we can combine the different results arrays using concat()
results = results.concat(domCrawler(children[i], className));
}
}
return results;
}
return function(className) {
return domCrawler(document.body, className);
};
})();
1 Like
You’re welcome - glad I could help!