The previousElementSibling property returns the previous element of the specified element.
Get the HTML content of the previous sibling of a list item:
var x = document.getElementById("item2").previousElementSibling.innerHTML;
Click the button to get the HTML content of the previous sibling of the second list item.
<!DOCTYPE html> <html> <body> <p>Example list:</p> <ul> <li id="item1">CSS (first li)</li> <li id="item2">HTML (second li)</li> <li id="item3">Java (third li)</li> </ul>/*ww w . ja v a 2s .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>
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, not including text and comment nodes.
This property is read-only.
Use the nextElementSibling property to return the next element of the specified element.
Use the children property to return any child element of a specified element.
The previousElementSibling property returns a Node object representing the previous sibling of an element, or null if there is no previous sibling.