Javascript DOM HTML Node previousSibling Property

Introduction

Get the HTML content of the previous sibling of a list item:

var x = document.getElementById("item2").previousSibling.innerHTML;

Click the button to get the HTML content of the previous sibling of the second list item.

Whitespace inside elements is considered as text, and text is considered as nodes.

If you add whitespace between the two li elements, the result will be "undefined".

View in separate window

<!DOCTYPE html>
<html>
<body>

<p>Example list:</p>

<ul><li id="item1">Coffee (first li)</li><li id="item2">Tea (second li)</li></ul>
<button onclick="myFunction()">Test</button>
<p id="demo"></p>

<script>
function myFunction() {//w  w  w.j av  a2 s .  c  o  m
  var x = document.getElementById("item2").previousSibling.innerHTML;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The previousSibling property returns the previous node of the specified node in the same tree level.

The returned node is returned as a Node object.

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

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

This property is read-only.

We can use the nextSibling property to return the next node of the specified node, in the same tree level.

We can use the childNodes property to return any child node of a specified node.

The previousSibling property returns null if there is no previous sibling.




PreviousNext

Related