Javascript Reference - HTML DOM previousSibling Property








The previousSibling property returns the previous node from a node in the same level as a Node object.

If there is no previousSibling node, the return value is null.

Browser Support

previousSibling Yes Yes Yes Yes Yes

Syntax


var v = node.previousSibling;

Return Value

The previous sibling of the node as a Node object.





Example

The following code shows how to get the previousSibling of a list item.


<!DOCTYPE html>
<html>
<body>
<!--from w  ww .  jav a  2 s . c  o  m-->
<p>test</p>
<ul id="myList"><li id="item1">A</li><li id="item2">B</li></ul>
<p>test</p>
<p id="demo">test</p>

<button onclick="myFunction()">test</button>

<script>
function myFunction()
{
    var itm=document.getElementById("item2");
    var x=document.getElementById("demo");  
    x.innerHTML=itm.previousSibling.id;
}
</script>
</body>
</html>

The code above is rendered as follows: