HTML DOM Element parentElement attribute

Definition and usage

parentElement properties return the parent element of the specified element.

parentElement and parentNode The difference between them is that if the parent node is not an element node, then parentElement Returns null:

document.body.parentNode; // Returns <html> element
document.body.parentElement; // Returns <html> element
document.documentElement.parentNode; // Returns document node
document.documentElement.parentElement; // Returns null (<html> has no parent ELEMENT node)

In most cases, which attribute to use does not matter, but parentNode It may be the most popular.

This property is read-only.

HTML node and element

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

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

ElementWhitespace between them is also a text node.

while elements are just element nodes.

Child node and child element

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

children ReturnsChild elementrather than text and comment nodes).

Sibling and element sibling

siblingare referred to as 'brother' and 'sister'.

siblingare nodes that have the same parent node (in the same childNodes in the list).

Element siblingare elements that have the same parent element (in the same children in the list).

Instance

Example 1

Get the node name of the parent element of the <li> element:

var x = document.getElementById("myLI").parentElement.nodeName;

Try it yourself

Example 2

Clicking the element (<span>) can hide its parent element (<div>):

<div>
  <span onclick="this.parentElement.style.display = 'none';">x</span>
</div>

Try it yourself

Syntax

node.parentElement

Return value

Type Description
Element object Represents the parent element node of the node.
null If the node has no parent node.

Browser support

element.parentElement It is a feature of DOM Level 3 (2004).

All browsers fully support it:

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