HTML DOM Element previousSibling

Example

Return the HTML content of the previous sibling of a list item:

document.getElementById("item2").previousSibling.innerHTML;
Try it Yourself »

Description

The previousSibling property returns the previous node on the same tree level.

The previousSibling property returns a node object.

The previousSibling property is read-only.

Important!

previousSibling returns the previous sibling node: An element node, a text node, or a comment node.

Whitespace between elements are also text nodes.

Alternative:

The previousElementSibling Property

previousElementSibling returns the previous sibling element (ignores text and comments).

See Also:

The nextSibling Property

The firstChild Property

The lastChild Property

The childNodes Property

The hasChildNodes() Method

Nodes vs Elements

In the HTML DOM terminology:

Nodes are all nodes (element nodes, text nodes, and comment nodes).

Whitespace between elements are also text nodes.

Elements are only element nodes.


Siblings vs Element Siblings

Siblings are "brothers" and "sisters".

Siblings are nodes with the same parent (in the same childNodes list).

Element Siblings are elements with the same parent (in the same children list).


childNodes vs children

childNodes returns child nodes (element nodes, text nodes, and comment nodes).

children returns child elements (not text and comment nodes).


nextSibling vs nextElementSibling

nextSibling returns the next node (an element node, a text node or a comment node). Whitespace between elements are also text nodes.

nextElementSibling returns the next element (not text and comment nodes).


previousSibling vs previousElementSibling

previousSibling returns the previous node (an element node, a text node or a comment node). Whitespace between elements are also text nodes.

previousElementSibling returns the previous element (not text and comment nodes).


Syntax

element.previousSibling
or
node.previousSibling

Return Value

Type Description
NodeThe previous sibling of the node.
null if no previous sibling exists.

Browser Support

element.previousSibling is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.