Skip to content

Instantly share code, notes, and snippets.

@deadkff01
Last active December 10, 2018 13:12
Show Gist options
  • Save deadkff01/4a32ab84c29ab4ee55b9a7190859cc24 to your computer and use it in GitHub Desktop.
Save deadkff01/4a32ab84c29ab4ee55b9a7190859cc24 to your computer and use it in GitHub Desktop.
Get DOM elements by class name
// recursive method
const getElementsByClassNameRec = (className) => {
let nodeList = []
function find(node) {
if (node.classList && node.classList.contains(className))
nodeList.push(node)
for (let i = 0; i < node.childNodes.length; i++)
find(node.childNodes[i])
return nodeList
}
find(document.body)
return nodeList
};
// supreme empilhar os elementos e ir substituindo pelos filhos
// array.from coloca todos os filhos do elemento pai em um array
const getElementsByClassName = (className) => {
let stack = [document.body]
let nodeList = []
do {
let node = stack.pop()
if (node.classList && node.classList.contains(className))
nodeList.push(node)
stack = stack.concat(Array.from(node.childNodes).reverse())
} while (stack.length > 0)
return nodeList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment