Skip to content

Instantly share code, notes, and snippets.

@gh-o-st
Created October 13, 2021 01:05
Show Gist options
  • Select an option

  • Save gh-o-st/40559008c5d2eef7e4b04be97088c514 to your computer and use it in GitHub Desktop.

Select an option

Save gh-o-st/40559008c5d2eef7e4b04be97088c514 to your computer and use it in GitHub Desktop.
Find the next/prev matching sibling using vanilla JS
const getPreviousMatch = (el, target) => {
// Get the next matching element
let match = el.previousElementSibling;
// If there's no selector, return the first element
if (!target) return match;
// If the element matches our selector, use it
// If not, jump to the next element and continue the loop
while (match) {
if (match.matches(target)) return match;
match = match.previousElementSibling;
}
};
const getNextMatch = (el, target) => {
// Get the next matching element
let match = el.nextElementSibling;
// If there's no selector, return the first element
if (!target) return match;
// If the element matches our selector, use it
// If not, jump to the next element and continue the loop
while (match) {
if (match.matches(target)) return match;
match = match.nextElementSibling
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment