- parentNode:
The parent node property is read only property which returns us the name of the parent node of the selected node as a node object. The Node object represents a single node in the document tree and a node can be an element node, text node or more.Syntax:
node.parentNode
Return Value: The parent node property returns the parent node object if present or else it will return “null”.
Example:
<!DOCTYPE html>
<
html
>
<
body
>
<!--setting styles for our document-->
<
style
>
p {
color: green;
}
</
style
>
<
p
>GeeksForGeeks</
p
>
<
div
>
<
p
id
=
"gfg"
>Click the button to get the
node name of the parent node.</
p
>
<!--here 'p' element is inside 'div' element
meaning that 'div' is the parent of 'p' element here-->
</
div
>
<
button
onclick
=
"myParentNode()"
>Try it</
button
>
<
p
id
=
"text"
></
p
>
<
script
>
function myParentNode() {
var geek = document.getElementById("gfg").parentNode.nodeName;
/*appending parent node to the 'p' element with id named text*/
document.getElementById("text").innerHTML = geek;
}
</
script
>
</
body
>
</
html
>
chevron_rightfilter_noneOutput:
- parentElement:
The parent element is read only property which returns the parent element of the selected element.The element object represents an HTML element, like P, DIV, etc.
Syntax:
node.parentElement
Return Value: The parentElement property returns an element object representing parent element if present or else it will return null.
Example:
<!DOCTYPE html>
<
html
>
<
body
>
<!--setting styles for our document-->
<
style
>
p,
ol {
color: green;
}
</
style
>
<
p
>GeeksForGeeks Courses</
p
>
<
ol
>
<
li
id
=
"geek"
>DSA</
li
>
<
li
>Interview Preparation</
li
>
<
li
>Geeks Classes</
li
>
</
ol
>
<
p
>Click the button to get the node
name of the parent element</
p
>
<
button
onclick
=
"myParentElement()"
>
Click to know the parent element
</
button
>
<!--here 'li' element is inside 'ol' element meaning
that 'ol' is the parent of 'li' element here-->
<
p
id
=
"gfg"
></
p
>
<
script
>
function myParentElement() {
var text = document.getElementById(
"geek").parentElement.nodeName;
document.getElementById("gfg").innerHTML = text;
}
</
script
>
</
body
>
</
html
>
chevron_rightfilter_noneOutput:
Difference:
Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same. For instance:// returns the document node document.documentElement.parentNode; // returns null document.documentElement.parentElement;
The HTML element (document.documentElement) doesn’t have a parent that is an element, it is a node, therefore, the parent element is null.
Supported Browsers: The browsers supported by parentNode and DOM parentElement property are listed below:
- Google Chrome
- Internet Explorer
- Firefox
- Apple Safari
- Opera
Data Structures and Algorithms – Self Paced Course
View Details