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:
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