Created
April 6, 2018 17:35
-
-
Save michaelwhyte/1d702ca6f2fca95d28f898200239c835 to your computer and use it in GitHub Desktop.
Get sibling elements with an optional filter selector
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
| // Get Sibling Elements with Filter | |
| // The getSiblings() and getChildren() code has been customized by @michaelwhyte | |
| // from code found on this Stackoverflow question: | |
| // https://stackoverflow.com/questions/842336/is-there-a-way-to-select-sibling-nodes | |
| // | |
| // The code from the stackoverflow question is based on | |
| // jQuery's siblings() code | |
| function getSiblings(n, filter) { | |
| return getChildren(n.parentNode.firstChild, n, filter); | |
| } | |
| // Get Children Elements | |
| function getChildren(n, skipMe, filter){ | |
| let r = []; | |
| for ( ; n; n = n.nextSibling ){ | |
| if ( n.nodeType == 1 && n != skipMe){ | |
| if(filter){ | |
| if(n.matches(filter)){ | |
| r.push( n ); | |
| } | |
| }else{ | |
| r.push( n ); | |
| } | |
| } | |
| } | |
| return r; | |
| } | |
| // Example Usage | |
| // Example - No Filter | |
| const someEl = document.getElementById('#foo'); | |
| const siblings = getSiblings(someEl); | |
| // Example - With Filter | |
| const someOtherEl = document.getElementById('#bar'); | |
| const siblings = getSiblings(someOtherEl, 'div'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment