Skip to content

Instantly share code, notes, and snippets.

@mattkenefick
Last active July 13, 2024 16:07
Show Gist options
  • Save mattkenefick/872f887fcb905d3c5094390f37e4ce1f to your computer and use it in GitHub Desktop.
Save mattkenefick/872f887fcb905d3c5094390f37e4ce1f to your computer and use it in GitHub Desktop.
parentSelector
// interface Element {
// parentSelector(selector: string): Element | null;
// previousSelector(selector: string, traverseUpwards?: boolean): Element | null;
// previousSelectorAll(selector: string, traverseUpwards?: boolean): Element[];
// }
/**
* Traverse upward from an existing element.
*
* @param string selector
* @return HTMLElement | null
*/
Element.prototype.parentSelector = function(selector) {
let element = this;
while (element) {
if (element.matches(selector)) {
return element;
}
element = element.parentElement;
}
return null;
};
/**
* Travese backwards and then upwards to find matching selector.
*
* @param string selector
* @param boolean traverseUpwards
* @return HTMLElement | null
*/
Element.prototype.previousSelector = function(selector, traverseUpwards = false) {
let element = this;
while (element) {
let sibling = element.previousElementSibling;
while (sibling) {
if (sibling.matches(selector)) {
return sibling;
}
sibling = sibling.previousElementSibling;
}
if (traverseUpwards) {
element = element.parentElement;
if (element && element.matches(selector)) {
return element;
}
}
}
return null;
};
/**
* Travese backwards and then upwards to find matching selectors.
*
* @param string selector
* @param boolean traverseUpwards
* @return HTMLElement[] | null
*/
Element.prototype.previousSelectorAll = function(selector, traverseUpwards = false) {
const elements = [];
let element = this;
while (element) {
let sibling = element.previousElementSibling;
while (sibling) {
if (sibling.matches(selector)) {
elements.push(sibling);
}
sibling = sibling.previousElementSibling;
}
if (traverseUpwards) {
element = element.parentElement;
if (element && element.matches(selector)) {
elements.push(element);
}
}
}
return elements;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment