Reputation: 63
After several attempts of hardcoding a recursive getElementsByClassName method, I settled with the following:
var getElementsByClassName = function(className) {
var result = [];
function inspect(element) {
var children = element.children;
for(var i = 0; i < children.length; i++) {
if(children[i].classList.contains(className)) {
result.push(children[i]);
}
if(children[i].hasChildNodes) {
inspect(children[i]);
}
}
}
inspect(document);
return result;
};
However, I can't figure why this solution doesn't work, considering className returns the value we can test against:
var getElementsByClassName = function(className) {
var result = [];
function inspect(element) {
if (element.className === className) result.push(element);
var children = element.children;
for(var i = 0; i < children.length; i++) {
inspect(children[i]);
}
}
inspect(document);
return result;
};
Thanks for the help, in advance, and if you have any other suggestions for improving my code, please let me know.
Upvotes: 0
Views: 1643
Reputation: 11
heres a solution for u that sort of uses your algorithm, but there are better ways to implement and you can also do this without an inner function.
var getElementsByClassName = function(className) {
var result = [];
function inspect(element, result) {
var children = element.children;
var parts = element.className.split(' ');
if(parts.indexOf(className) >= 0){
result.push(element);
}
for(var i = 0; i < children.length; i++) {
inspect(children[i], result);
}
}
inspect(document.body, result);
return result;
};
Upvotes: 1