使用 JavaScript 访问父元素
以下是使用 JavaScript 访问父元素的代码 −
示例
<!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>
输出
单击任何 div 区域后,将生成以下输出 −
广告