Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DarrenSem/4d37711fb71a484b6ed2356c60e3c94a to your computer and use it in GitHub Desktop.
Save DarrenSem/4d37711fb71a484b6ed2356c60e3c94a to your computer and use it in GitHub Desktop.
above.js (PARENT element, levels = #) + next.js (SIBLING element, levels = #) helper functions instead of foo.parentElement.parentElement.parentElement etc.
// above.js (PARENT element, levels = #) + next.js (SIBLING element, levels = #) helper functions instead of foo.parentElement.parentElement.parentElement etc.
// https://gist.github.com/DarrenSem/4d37711fb71a484b6ed2356c60e3c94a
// PARENT element: ...
const above = (startingElement, levels = 1) => {
let el = startingElement;
while ( levels-- && (el = el?.parentElement) );
return el || null;
};
// ... cf. SIBLING element:
const next = (startingElement, count = 1) => {
let el = startingElement;
while ( count-- && (el = el?.nextElementSibling) );
return el || null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment