Created
April 28, 2017 19:48
-
-
Save ArchangelGabriel/b7b315d186761992d2350b93c0faa413 to your computer and use it in GitHub Desktop.
Implement document.getElementsByClassName from scratch.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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