JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to get the parent element in JavaScript?

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.


<!DOCTYPE html>
  <title>How to access element's parent node in JavaScript</title>
    <p id="main-paragraph">This is a paragraph element.</p>
  <script src="app.js"></script>

JavaScript Code: app.js

let paragraph = document.getElementById('main-paragraph');
let parentElement = paragraph.parentNode;"red";

In this code, the parent container of a paragraph element is accessed, and then the background color is changed.

Recommended Posts