Accessing a parent Element using JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code for accessing a parent element using JavaScript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .result {
      font-size: 18px;
      font-weight: 500;
      color: #8a2be2;
   .parent3 {
      display: inline-block;
      margin: 10px;
   .child3 {
      width: 70px;
      height: 70px;
   .child1 {
      background-color: red;
   .child2 {
      background-color: pink;
   .child3 {
      background-color: blue;
<h1>Accessing a parent Element using JavaScript</h1>
<div class="parent1">
<div class="child1">Child 1</div>
<div class="parent2">
<div class="child2">Child 2</div>
<div class="parent3">
<div class="child3">Child 3</div>
<br />
<div class="result"></div>
<h3>Click on the any of the above div to know its parent element</h3>
   let resEle = document.querySelector(".result");
   document.querySelector(".child3").addEventListener("click", (event) => {
      resEle.innerHTML =
      "The parent node is " +;
   document.querySelector(".child1").addEventListener("click", (event) => {
      resEle.innerHTML =
      "The parent node is " +;
   document.querySelector(".child2").addEventListener("click", (event) => {
      resEle.innerHTML =
      "The parent node is " +;


On clicking any of the divs, the following output will be produced −

Updated on 18-Jul-2020 07:16:54