Traversing with ParentNode and Children

In this approach, We can use parentNode and children properties to manually traverse the DOM tree.

Example: The example below shows a Program Given a DOM tree and a target element, return the previous left sibling By Traversing with parentNode and children.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Example2</title>
</head>

<body>
    <div id="sibling1">Sibling 1</div>
    <div id="sibling2">Sibling 2</div>
    <div id="sibling3">Sibling 3</div>
    <script>
        let targetElement = 
            document.getElementById('sibling2');
        let previousSibling = null;
        let children = targetElement.parentNode.children;
        for (let i = 0; i < children.length; i++) {
            if (children[i] === targetElement && i > 0) {
                previousSibling = children[i - 1];
                break;
            }
        }
        console.log(previousSibling ? 
                    previousSibling.id : 
                    'No previous sibling');
    </script>
</body>

</html>

Output:

Output

JavaScript Program to Return the Previous Left Sibling

In the Document Object Model (DOM), every element is a node. So, Nodes can have parent, child, and sibling relationship nodes. So let’s find out how to find the previous left sibling of a target element in the DOM using JavaScript.

These are the following approaches:

Table of Content

  • Using previousElementSibling Property
  • By Traversing with parentNode and children
  • By Using NodeIterator

Similar Reads

Using previousElementSibling Property

In this approach, the previousElementSibling property returns the previous sibling element which is an element node....

Traversing with ParentNode and Children

In this approach, We can use parentNode and children properties to manually traverse the DOM tree....

By Using NodeIterator

A NodeIterator is used to get the document and find the previous sibling node. This method is useful for complex traversals....