Created
October 13, 2021 01:05
-
-
Save gh-o-st/40559008c5d2eef7e4b04be97088c514 to your computer and use it in GitHub Desktop.
Find the next/prev matching sibling using vanilla JS
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 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