HTML DOM Element previousElementSibling 属性

定义和用法

previousElementSibling 属性返回同一树级别中的前一个元素。

previousElementSibling 属性是只读的。

另请参阅:

nextElementSibling 属性

children 属性

firstElemenChild property

lastElemenChild property

childElementCount property

HTML node and element

in HTML DOM(Document Object Model), the HTML document is a collection of nodes that have (or do not have) child nodes.

Noderefers to element nodes, text nodes, and comment nodes.

Elementspaces between them are also text nodes.

while element is just an element node.

Sibling vs element sibling

Siblingis 'brother' and 'sister'.

Siblingis a node that has the same parent node (in the same childNodes list).

Element siblingis an element that has the same parent element (in the same children list).

Child nodes vs child elements

childNodes ReturnsChild node(element node, text node, and comment node).

children ReturnsChild element(not text and comment nodes).

nextSibling vs nextElementSibling

nextSibling Returns the nextNode(element node, text node, or comment node). The spaces between elements are also text nodes.

nextElementSibling Returns the nextElement(does not return text and comment nodes).

previousSibling vs previousElementSibling

previousSibling Returns the previousNode(element node, text node, or comment node). The spaces between elements are also text nodes.

previousElementSibling Returns the previousElement(does not return text and comment nodes).

Example

Returns the HTML content of the previous sibling:

let text = element.previousElementSibling.innerHTML;

Try it yourself

Syntax

element.previousElementSibling

Return value

Type Description
Element Previous sibling element.
null if there is no previous sibling.

Browser support

element.previousElementSibling is DOM Level 3 (2004) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Ci gaba da 9-11 Ci gaba da Ci gaba da Ci gaba da Ci gaba da