Last active
August 24, 2021 12:09
-
-
Save wiegertschouten/b1a342343a6ec20b7ff84e3a828474ec to your computer and use it in GitHub Desktop.
Simple DOM selection utility
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
document.findFirst = HTMLElement.prototype.findFirst = function(selector) { | |
return this.querySelector(selector); | |
} | |
document.findAll = HTMLElement.prototype.findAll = function(selector) { | |
return [...this.querySelectorAll(selector)]; | |
} | |
window.findFirst = document.findFirst.bind(document); | |
window.findAll = document.findAll.bind(document); |
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
const oneDiv = findFirst('div'); | |
const allDivs = findAll('div'); | |
const oneParagraphInsideOneDiv = oneDiv.findFirst('p'); | |
const allParagraphsInsideOneDiv = oneDiv.findAll('p'); | |
const oneParagraphInsideAllDivs = allDivs.map(div => div.findFirst('p')); | |
const allParagraphsInsideAllDivs = allDivs.map(div => div.findAll('p')).flat(); // Might lead to duplicate elements in array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment