Skip to content
This repository has been archived by the owner on Nov 29, 2023. It is now read-only.

Commit

Permalink
changed: refactored _getSiblingElements
Browse files Browse the repository at this point in the history
  • Loading branch information
MartijnR committed Apr 28, 2021
1 parent f9a5060 commit b0cd797
Showing 1 changed file with 10 additions and 18 deletions.
28 changes: 10 additions & 18 deletions src/js/dom-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* @return {Array<Node>} Array of sibling nodes plus target element.
*/
function getSiblingElementsAndSelf( element, selector ) {
return _getSiblingElements( element, selector, [ element ] );
return _getSiblingElements( element, selector, true );
}

/**
Expand Down Expand Up @@ -52,29 +52,21 @@ function getSiblingElement( element, selector = '*' ){
*
* @param {Node} element - Target element.
* @param {string} [selector] - A CSS selector.
* @param {Array<Node>} [startArray] - Array of nodes to start with.
* @param {boolean} [includeSelf] - Whether to include self.
* @return {Array<Node>} Array of sibling nodes.
*/
function _getSiblingElements( element, selector = '*', startArray = [] ) {
const siblings = startArray;
let prev = element.previousElementSibling;
let next = element.nextElementSibling;
// TODO: check if iteration approach used by getSiblingElement is faster. It would be more elegant.
while ( prev ) {
if ( prev.matches( selector ) ) {
siblings.unshift( prev );
}
prev = prev.previousElementSibling;
}
function _getSiblingElements( element, selector = '*', includeSelf = false ) {
const results = [];
let current = element.parentElement.firstElementChild;

while ( next ) {
if ( next.matches( selector ) ) {
siblings.push( next );
while ( current ) {
if ( ( current === element && includeSelf ) || ( current !== element && current.matches( selector ) ) ){
results.push( current );
}
next = next.nextElementSibling;
current = current.nextElementSibling;
}

return siblings;
return results;
}

/**
Expand Down

0 comments on commit b0cd797

Please sign in to comment.