The previousSibling property is used to return the previous node of the specified node as Node object or null if the specified node is the first in the list. It is a read-only property.
Syntax
node.previousSiblingReturn value: This property returns a previous sibling of the specified node or null if the current node has no previous sibling.
Example: In this example, we will use previousSibling property
<!--Driver Code Starts-->
<html>
<head>
<title>DOM previousSibling Property</title>
</head>
<body style="text-align: center">
<h1 style="color:green">
GeeksforGeeks
</h1>
<h2>
DOM previousSibling Property
</h2>
<div>
<span id="p1">GeeksforGeeks! </span><span id="p2">
A computer science portal for geeks.
</span>
</div>
<br>
<button onclick="geek()">Click me!</button>
<br><br>
<p id="p" style="margin:auto; width: 40%"></p>
<!--Driver Code Ends-->
<script>
function geek() {
let x = document.getElementById("p2")
.previousSibling.innerHTML;
document.getElementById("p").innerHTML = x;
document.getElementById("p").style.color = "white";
document.getElementById("p").style.background = "green";
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- It returns the immediately preceding node of any type in the parent’s childNodes list (Element, Text, Comment, etc.), or null if the current node is the first child. This makes it different from previousElementSibling, which skips non-element nodes and only returns the previous Element.
- Whitespace text nodes frequently appear as siblings. Browsers insert Text nodes for whitespace (spaces, newlines, tabs) in the source HTML. As a result, previousSibling often returns a whitespace Text node instead of the previous element you might expect. For element-only navigation, use previousElementSibling instead.