previousElementSibling property

The previousElementSibling property contains the previous element that is in the same parent. If there is no such element, then null is returned.

Syntax

javascriptelement.previousElementSibling;

Example

The element #elem is given. Let's display the text of his neighbor from above:

html<p>sibling</p>
<p id="elem">elem</p>
javascriptlet elem = document.querySelector('#elem');
let text = elem.previousElementSibling.textContent;

console.log(text);

The code execution result:

javascript'sibling'

Example

If there is no neighbor above or it is located not in the parent of our element, null is also returned:

html<p>sibling</p>
<div>
  <p id="elem">elem</p>
</div>
javascriptlet elem = document.querySelector('#elem');
console.log(elem.previousElementSibling);

The code execution result:

javascriptnull

See also