Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Accessing a parent Element using JavaScript
Following is the code for accessing a parent element using JavaScript −
Example
<!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 −

Advertisements