JavaScript’s Node.parentNode
read-only property returns the Node
’s parent node or null
if the Node
does not have a parent node.
Value
A Node
object or null
if the node does not have a parent node.
Examples
Here is an example of using the parentNode
property.
Suppose we have the following HTML elements:
<div>
<p>You can do wonderful things with JavaScript.</p>
</div>
How can we make sure with JavaScript that the p
element has a parent node named “DIV”?
Well, we can select the element with the querySelector()
method and use the parentNode
and nodeName
properties:
let p = document.querySelector('p');
console.log(p.parentNode.nodeName);
The last line logs the name of the parent node to the console of your browser.
Additional notes
You may have wondered why the name of the p
element is in uppercase. That is because the names of HTML elements are in uppercase, whereas the names of XML elements are in lowercase.
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
parentNode |
1 | 12 | 1 | 5.5 | 7 | 1.1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 |