JavaScript - parentNode vs parentElement vs offsetParent
In this article, we would like to show you the differences between parentNode
, parentElement
and offsetParent
in JavaScript.
1. parentNode
Syntax:
node.parentNode
The parentNode
property is a read-only property that returns 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. If there's no parent node object the method returns null
.
2. parentElement
Syntax:
node.parentElement
The parentElement
is a read-only property that returns the parent element of the selected element. The element object represents an HTML element, like P, DIV, etc. If there's no parent element object the method returns null
.
3. offsetParent
Syntax:
element.offsetParent
The offsetParent
is a read-only property that returns a reference to the element which is the closest (nearest in the containment hierarchy) positioned ancestor element. If there is no positioned ancestor element, the nearest ancestor td
, th
, table
will be returned, or the body
if there are no ancestor table elements either.
The offsetParent returns null
when:
- the element or its parent has the display property set to
none
, - the element position property is set to
fixed
(Firefox returnsbody
element), - the element is
<body>
or<html>
.
4. Differences
1. The main difference is that the parentElement
and offsetParent
return null
if the parent is not an element node.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<script>
// returns the document node
var parentNode = document.documentElement.parentNode;
console.log(parentNode);
// returns null
var parentElement = document.documentElement.parentElement;
console.log(parentElement);
// returns null
var offsetParent = document.documentElement.offsetParent;
console.log(offsetParent);
</script>
</body>
</html>
2. The parentElement
is new to Firefox9 and to DOM4,
3. The parentElement
is undefined for SVG elements in Internet Explorer (whereas parentNode is defined),
4. The parentElement
was a non-standard extension for Internet Explorer, parentNode
and offsetParent
became standard earlier,
5. The offsetParent
is the closest parent that has relative
or absolute
position, or the body
of the page, while parentNode
is the direct parent, no matter what the position is.