Element previousSibling Property - Javascript DOM

Javascript examples for DOM:Element previousSibling

Description

The previousSibling property returns the previous node with same parent as a Node object.

previousSibling returns the previous sibling node as an element node, a text node or a comment node

previousElementSibling returns the previous sibling node as an element node ignoring text and comment nodes.

This property is read-only.

Return Value

A Node object, representing the previous sibling of the node, or null if there is no previous sibling

The following code shows how to get the HTML content of the previous sibling of a list item:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<p>Example list:</p>

<ul>
   <li id="item1">(first li)</li>
   <li id="item2">(second li)</li>
</ul>//w ww.jav a 2s.c  om

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

<p id="demo"></p>

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

</body>
</html>

Related Tutorials