Skip to content

JavaScript previous sibling

  • by

In JavaScript, you can access the previous sibling of an element using the previousSibling property. This property returns the node that immediately precedes the specified element in its parent’s childNodes list, including text nodes, comment nodes, and other element nodes.

Here’s the syntax for accessing the previous sibling element in JavaScript:

var element = document.getElementById("myElement");
var previousSibling = element.previousSibling;

Note: The previousSibling property can sometimes return nodes that are not element nodes (e.g., text nodes representing whitespace or line breaks). If you specifically want the previous sibling element node, you can use a loop to traverse the previousSibling chain until you find an element node.

Get the previous sibling in the JavaScript example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>Previous Sibling Example</title>
</head>
<body>
  <div id="parent">
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
    <p>This is the third paragraph.</p>
  </div>

  <script>
    // Get the second paragraph element
    var secondParagraph = document.getElementsByTagName('p')[1];

    // Access the previous sibling element
    var previousSibling = secondParagraph.previousSibling;

    // Traverse to the previous sibling until an element node is found
    while (previousSibling && previousSibling.nodeType !== Node.ELEMENT_NODE) {
      previousSibling = previousSibling.previousSibling;
    }

    if (previousSibling) {
      console.log(previousSibling.innerHTML); 
    }
  </script>
</body>
</html>

Output:

JavaScript previous sibling

In this code, we added a while loop that keeps traversing to the previous sibling until an element node is found. This helps skip over any text nodes, comment nodes, or whitespace nodes.

Now, when you run this code, you should see the desired output in the console, which is the content of the previous paragraph (“This is the first paragraph.”).

Do comment if you have any doubts or suggestions on this JS code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *