Skip to content

JavaScript previousElementSibling Property

  • by

In JavaScript, the previousElementSibling property is used to get the previous sibling element of a specified element. It returns the element immediately preceding the specified element in the DOM (Document Object Model) tree.

Here is the syntax:

var previousElement = element.previousElementSibling;
  • element is the DOM element for which you want to retrieve the previous sibling element.
  • previousElementSibling is the property that returns the previous sibling element.

Note: the previousElementSibling property returns null if there is no previous sibling element.

JavaScript previousElementSibling property example

Simple example code.

<!DOCTYPE html>
<html>
<body>

<ul>
  <li>Item 1</li>
  <li id="target">Item 2</li>
  <li>Item 3</li>
</ul>

<script>
  var targetElement = document.getElementById("target");
  var previousElement = targetElement.previousElementSibling;
  
  console.log(previousElement.textContent);
</script>

</body>
</html>

Output:

JavaScript previousElementSibling Property

The previousElementSibling property only returns elements, excluding any text nodes or other non-element nodes.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading