Every HTML element has a parentNode
property that returns the parent node of that element.
In order to access the element's parent node, first of all, you have to select that element using getElementById()
, querySelector()
, and other methods. Then, call parentNode
property to get the parent of that element.
The following example will explain to you how to access the element's parent node.
HTML Code
<!DOCTYPE html> <html> <head> <title>How to access element's parent node in JavaScript</title> </head> <body> <div> <p id="main-paragraph">This is a paragraph element.</p> </div> <script src="app.js"></script> </body> </html>
JavaScript Code: app.js
let paragraph = document.getElementById('main-paragraph'); let parentElement = paragraph.parentNode; parentElement.style.backgroundColor="red";
In this code, the parent container of a paragraph element is accessed, and then the background color is changed.