W3cubDocs

/Web APIs

Node: previousSibling property

The read-only previousSibling property of the Node interface returns the node immediately preceding the specified one in its parent's childNodes list, or null if the specified node is the first in that list.

Note: Browsers insert text nodes into a document to represent whitespace in the source markup. Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a whitespace text node rather than the actual element the author intended to get.

See Whitespace in the DOM for more information.

You can use previousElementSibling to get the previous element node (skipping text nodes and any other non-element nodes).

To navigate the opposite way through the child nodes list use Node.nextSibling.

Value

A Node representing the previous sibling of the current node, or null if there are none.

Examples

The following examples demonstrate how previousSibling works with and without text nodes mixed in with elements.

First example

In this example, we have a series of img elements directly adjacent to each other, with no whitespace between them.

html

<img id="b0" /><img id="b1" /><img id="b2" />

js

document.getElementById("b1").previousSibling; // <img id="b0">
document.getElementById("b2").previousSibling.id; // "b1"

Second example

In this example, there are whitespace text nodes (line breaks) between the img elements.

html

<img id="b0" />
<img id="b1" />
<img id="b2" />

js

document.getElementById("b1").previousSibling; // #text
document.getElementById("b1").previousSibling.previousSibling; // <img id="b0">
document.getElementById("b2").previousSibling.previousSibling; // <img id="b1">
document.getElementById("b2").previousSibling; // #text
document.getElementById("b2").previousSibling.id; // undefined

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
previousSibling 1 12 1 5.5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling