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
element.previousElementSibling;
Example
The element #elem is given. Let's
display the text of his neighbor from above:
<p>sibling</p>
<p id="elem">elem</p>
let elem = document.querySelector('#elem');
let text = elem.previousElementSibling.textContent;
console.log(text);
The code execution result:
'sibling'
Example
If there is no neighbor above or it
is located not in the parent of our
element, null is also returned:
<p>sibling</p>
<div>
<p id="elem">elem</p>
</div>
let elem = document.querySelector('#elem');
console.log(elem.previousElementSibling);
The code execution result:
null
See also
-
the
nextElementSiblingproperty
that contains a neighbor from below (next element)