Accessing a parent Element using JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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

Example

 Live Demo

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

Output

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

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

Advertisements