Last active
December 10, 2018 13:12
-
-
Save deadkff01/4a32ab84c29ab4ee55b9a7190859cc24 to your computer and use it in GitHub Desktop.
Get DOM elements by class name
This file contains hidden or 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
// 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
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName