如何使用 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; } .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>
输出
单击“此处单击”按钮时 -
广告