The previousElementSibling property returns the previous element sibling of a given element (or null if none exists). Unlike previousSibling, which can return any node type (including text or comment nodes), it only returns element nodes.
Syntax
node.previousElementSiblingReturn value: This property returns a previous sibling of the specified element or null if the current element has no previous sibling.
Example: In this example, we will use the previousElementSibling property.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM previousElementSibling Property</title>
</head>
<body>
<h2>DOM previousElementSibling Property</h2>
<h4>Web Languages:</h4>
<select id="languages" size="4">
<option>HTML</option>
<option>CSS</option>
<option>JavaScript</option>
<option>XML</option>
</select>
<br><br>
<button onclick="Geeks()">
Previous Element Sibling
</button>
<br><br>
<p id="p"></p>
<!--Driver Code Ends-->
<script>
function Geeks() {
let select = document.getElementById("languages");
let selectedOption = select.options[select.selectedIndex];
if (selectedOption.previousElementSibling) {
document.getElementById("p").textContent =
"Previous Element Sibling: " +
selectedOption.previousElementSibling.textContent;
} else {
document.getElementById("p").textContent =
"No Previous Element Sibling";
}
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- It returns only the previous Element sibling (skipping Text nodes, Comments, and other non-element nodes), or null if there is none. This makes it much more convenient than previousSibling when you only care about elements, because browsers frequently insert whitespace Text nodes between elements in the source HTML.
- It is available on both Element and CharacterData nodes (Text, Comment, etc.). Even when called on a text or comment node, it still returns the nearest previous Element sibling (or null), allowing consistent element-only navigation from any non-document-type child node.