다음은 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 중 하나를 클릭하면 다음과 같은 출력이 생성됩니다. -