다음은 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; } .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>
출력
'여기를 클릭' 버튼을 클릭하면 -