Pretty HTML adds text. A newline between tags is a text node.
previousSibling sees that text.nodeName is "#text".
previousElementSibling skips it. You get the previous <span>.
Rule of thumb. Want an element? Prefer previousElementSibling.
Example 3 — Walk Preceding Siblings
Loop with previousElementSibling until null (MDN pattern).
JavaScript
let el = document.getElementById("c").previousElementSibling;
while (el) {
console.log(el.textContent);
el = el.previousElementSibling;
}
// "B"
// "A"
Start before C. First value is C’s previous element sibling (B).
Loop while truthy.null ends the walk.
Visit each node. Log text (or do other work).
Advance.el = el.previousElementSibling moves one step backward.
Compatibility
Browser Support
Element.previousElementSibling is Baseline Widely available (MDN: since July 2015). Safe across modern and older evergreen browsers.
✓ Baseline · Widely available
Element.previousElementSibling
Read-only previous sibling Element or null — skips text and comments between tags.
99%Widely available
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
previousElementSiblingExcellent
Bottom line: Safe for production. Prefer it over previousSibling whenever you specifically need an Element sibling.
Frequently Asked Questions
The element immediately before the current one in the parent's children list, or null if there is no preceding element sibling.
No. MDN marks Element.previousElementSibling as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
previousSibling returns the previous node of any type (element, text, comment). previousElementSibling skips non-elements and returns only the previous Element.
It returns null when the current element is already the first element sibling.
Yes. Walk backward across element siblings by reading previousElementSibling repeatedly in a loop or step by step.
Yes. It is for navigation only — you cannot assign a different sibling to it.