How to get the Parent Node of DOM Element in JavaScript
Table of Contents
JavaScript has a lot of built-in functionality that makes working with the DOM on the web easy.
When you are working with DOM elements, a common thing you will want to do is get the parent node of an element.
In this post, we'll learn how to get the parent node of a DOM element in JavaScript.
How to get the parent node of a DOM element in JavaScript
Because of HTML's DOM-like structure, elements are arranged in a tree. This means that each element has a parent node, and each element can have multiple child nodes.
First, let's look at the HTML we'll be working with:
HTML<div class="parent">
<div class="child"></div>
</div>
Let's say we want to get the parent node of the child element. We can do this by first querying the DOM for the child element:
JAVASCRIPTconst child = document.querySelector(".child");
console.log(child);
HTML<div class="child"></div>
Then, we can get the parent node of the child element by using the parentNode
property:
JAVASCRIPTconst child = document.querySelector(".child");
const parent = child.parentNode;
console.log(parent);
HTML<div class="parent">
<div class="child"></div>
</div>
The only element that does not have a parent node is the document
element. This is because the document
element is the root of the DOM tree.
Other than the document
element, every other element has a parent node and so when you use the parentNode
property, you will always get an element back.
Conclusion
In this post, we learned how to get the parent node of a DOM element in JavaScript.
Simply query the DOM for the element you want to get the parent node of, and then use the parentNode
property to get the parent node.
Thanks for reading!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Getting Started with React
- How To Create a Modal Popup Box with CSS and JavaScript