When you’re developing a website or setting up the tagging and analytics for it, you will face a number of challenges. One of those challenges is navigating the Document Object Model (DOM), the tree-like structure that represents the elements on a web page.
Sometimes, navigating that map is a little trickier. Like when you need to get the parent element of an element and do something with it, which is what this tutorial will show you how to do.
How to Get the Parent of a DOM Element
node.parentElement() Web API. If the said element has a parent element, the method will return it. If it doesn’t, it will be
Here’s an example:
// Get the parent of an element const element = document.querySelector('#my-element'); const parentElement = element.parentElement;
In the code above, we start by selecting the element that we want to retrieve the parent node for using the
querySelector() method. In this case, we’ve selected an element with an ID of
my-element, but you could replace that with any valid CSS selector to select any element that you want.
Next, we use the
parentElement property to get the element’s parent. The
parentElement property returns the parent DOM element of the specified element, which can be any DOM element. Once we have the parent element, we can use it for whatever we need in our code, from manipulating it to extracting data from it.
parentNode property or the
previousSibling property. However, the
parentElement property is the most widely supported and most accurate approach.
The parentElement() vs. parentNode() Property
The main difference is that
parentElement is a property that specifically returns the parent DOM element of an element, while
parentNode is a property that returns the parent node of any node type — whether that’s an element, text, or even a comment node.
In practice, this means that
parentElement is the most practical to use if you’re only interested in retrieving the parent element of an element node, as it will always return an element node (or
null if the element has no parent element). However, if you’re working with a node that might not be an element node (e.g., a text node or a comment node), you would need to use