HTML Element .parentNode / parentElement
| Since: | DOM Level 1(1998) |
|---|
A property that retrieves the parent of an HTML element. parentNode returns the parent node, while parentElement returns the parent only if it is an HTML element.
Syntax
// Gets the parent node. var parent = element.parentNode; // Gets the parent only if it is an HTML element. var parent = element.parentElement;
Property List
| Property | Description |
|---|---|
| parentNode | Returns the parent node. The parent node may be an HTML element, a Document, or a DocumentFragment. Returns null if no parent exists. |
| parentElement | Returns the parent node only if it is an HTML element. Returns null if the parent is not an HTML element, such as a Document. |
Sample Code
sample_parentNode.html
<div id="bureau"> <ul id="inspectors"> <li id="kogami">Kogami Shinya</li> <li id="tsunemori">Tsunemori Akane</li> </ul> </div>
sample_parentNode.js
var kogami = document.getElementById("kogami");
// Pattern 1: Get the direct parent element
console.log(kogami.parentNode.id); // Outputs "inspectors"
console.log(kogami.parentElement.id); // Outputs "inspectors"
// Pattern 2: Traverse up to the grandparent
console.log(kogami.parentNode.parentNode.id); // Outputs "bureau"
// Pattern 3: Modify the parent element via a child element
var list = kogami.parentNode;
list.style.listStyleType = "none";
// Pattern 4: Identify the parent via a child and check its properties
var tsunemori = document.getElementById("tsunemori");
var parent = tsunemori.parentElement;
console.log(parent.children.length); // Outputs "2" (number of li elements inside ul)
// Pattern 5: The parent of the html element is Document, so parentElement is null
var html = document.documentElement;
console.log(html.parentNode.nodeName); // Outputs "#document"
console.log(html.parentElement); // Returns null
Notes
Both element.parentNode and element.parentElement retrieve the parent of an HTML element. In typical DOM operations they return the same result, but they differ when working with the <html> element: its parent is a Document node, not an HTML element. In that case, parentNode returns the Document, while parentElement returns null.
A common pattern is to get the parent of a child element and then call parentElement.removeChild() to remove the child. However, if you simply want to remove an element, using element.remove() is more concise.
To search for an ancestor element, use element.closest(), which efficiently finds a matching ancestor using a CSS selector.
Browser Compatibility
1 or earlier ×
4.5 or earlier ×
6 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.