DOM Question #4

Find all siblings of a given DOM element.

In this question we need to return all siblings so they can have same parent or different, but need to be on same level.

To solve this question BFS will be the most suitable algorithm. We will do level orde…


This content originally appeared on DEV Community and was authored by Shweta Kale

Find all siblings of a given DOM element.

In this question we need to return all siblings so they can have same parent or different, but need to be on same level.

Image description

To solve this question BFS will be the most suitable algorithm. We will do level order traversal and return nodes at current level if targetNode exist.

function getSiblings = (targetNode )=> {
  if(!targetNode ) return null;

  const queue= [targetNode , null];
  let nodesAtSameLevel = [];
  let currentLevelIncludeTarget = false;

  while(queue.length > 0){
    const currentN = queue.shift();

    if(currentN === targetNode) currentLevelIncludeTarget = true;

    if(currentN === null){
      if(currentLevelIncludeTarget){
        return nodesAtSameLevel;
      }
      nodesAtSameLevel = [];
      if(queue.length) queue.push(null);
    } else {
      nodesAtSameLevel.push(currentN);
      queue.push(...currentN.childNodes);
    }
  }
  return [];
}

If we want to return only immediate siblings of given node we can get parentNode and then return all its child nodes after removing targetNode.

Something like


 const getSiblings = (node) => {
  if (!node || !node.parentNode) return [];

  return Array.from(node.parentNode.childNodes).filter((sibling) => sibling !== node);
};


This content originally appeared on DEV Community and was authored by Shweta Kale


Print Share Comment Cite Upload Translate Updates
APA

Shweta Kale | Sciencx (2025-02-21T17:44:24+00:00) DOM Question #4. Retrieved from https://www.scien.cx/2025/02/21/dom-question-4/

MLA
" » DOM Question #4." Shweta Kale | Sciencx - Friday February 21, 2025, https://www.scien.cx/2025/02/21/dom-question-4/
HARVARD
Shweta Kale | Sciencx Friday February 21, 2025 » DOM Question #4., viewed ,<https://www.scien.cx/2025/02/21/dom-question-4/>
VANCOUVER
Shweta Kale | Sciencx - » DOM Question #4. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/02/21/dom-question-4/
CHICAGO
" » DOM Question #4." Shweta Kale | Sciencx - Accessed . https://www.scien.cx/2025/02/21/dom-question-4/
IEEE
" » DOM Question #4." Shweta Kale | Sciencx [Online]. Available: https://www.scien.cx/2025/02/21/dom-question-4/. [Accessed: ]
rf:citation
» DOM Question #4 | Shweta Kale | Sciencx | https://www.scien.cx/2025/02/21/dom-question-4/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.