Skip to content

Instantly share code, notes, and snippets.

@ArchangelGabriel
Created April 28, 2017 19:48
Show Gist options
  • Save ArchangelGabriel/b7b315d186761992d2350b93c0faa413 to your computer and use it in GitHub Desktop.
Save ArchangelGabriel/b7b315d186761992d2350b93c0faa413 to your computer and use it in GitHub Desktop.
Implement document.getElementsByClassName from scratch.
var getElementsByClassName = function(className) {
return getNodesWithClassName(document.childNodes, className);
};
var getNodesWithClassName = function(nodes, className) {
if (nodes.length === 0) return [];
return (hasClassOf(nodes[0], className) ? [nodes[0]] : [])
.concat(getNodesWithClassName(nodes[0].childNodes, className))
.concat(getNodesWithClassName([...nodes].slice(1), className));
};
var hasClassOf = function(element, className) {
return element.classList && element.classList.contains(className);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment