Skip to content

Instantly share code, notes, and snippets.

@wiegertschouten
Last active August 24, 2021 12:09
Show Gist options
  • Save wiegertschouten/b1a342343a6ec20b7ff84e3a828474ec to your computer and use it in GitHub Desktop.
Save wiegertschouten/b1a342343a6ec20b7ff84e3a828474ec to your computer and use it in GitHub Desktop.
Simple DOM selection utility
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);
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