Element previousElementSibling Property - Javascript DOM

Javascript examples for DOM:Element previousElementSibling

Description

The previousElementSibling property returns the previous element of the specified element with the same parent.

This property is read-only.

Return Value

A Node object, representing the previous sibling of an element, 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>/*from w w  w. j a  v  a 2  s. c o m*/

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

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

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

</body>
</html>

Related Tutorials