How to get the child element of a parent using JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code for getting the child element of a parent 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;
   }
   .child1,
   .child2,
   .child3 {
      display: none;
      margin: 10px;
      width: 70px;
      height: 70px;
   }
   .child1 {
      background-color: red;
   }
   .child2 {
      background-color: pink;
   }
   .child3 {
      background-color: blue;
   }
</style>
</head>
<body>
<h1>Get the child element of a parent using JavaScript</h1>
<div class="parent1">
<div class="child1">Child 1</div>
<div class="child2">Child 2</div>
<div class="child3">Child 3</div>
</div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to see the parent1 child elements</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let parentEle = document.querySelector(".parent1");
   BtnEle.addEventListener("click", (event) => {
      Array.from(parentEle.children).forEach((item) => {
         item.style.display = "inline-block";
      });
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −

raja
Published on 18-Jul-2020 07:17:51
Advertisements