DEV Community

Shweta Kale
Shweta Kale

Posted on • Edited on

DOM Question #4 All siblings

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.


const getRoot = (targetNode )=> {
  let parent = targetNode;
  while(parent.parentElement){
    parent = parent.parentElement;
  }
  return parent;
}

const getSiblings = (targetNode )=> {
  if(!targetNode ) return null;
  const root = getRoot(targetNode);
  const queue= [root, null];
  let nodesAtSameLevel = [];
  let currentLevelIncludeTarget = false;

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



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

Enter fullscreen mode Exit fullscreen mode

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.parentElement) return [];

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

Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay