Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Lấy element con (child element) của parent trong JavaScript


parentElement.children trả về HTMLCollection (live) chỉ chứa Element node (bỏ text node). Dùng Array.from() hoặc [...children] để dùng forEach.

Ví dụ

Parent có 3 child div ẩn. Nhấn nút hiển thị tất cả:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Get child elements</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: red; }
    .child2 { background: pink; }
    .child3 { background: blue; }
  </style>
</head>
<body>
  <h1>Lấy element con của parent trong 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">HIỂN THỊ CHILDREN</button>
  <h3>Nhấn nút để hiện các child div</h3>
  <script>
    const btn = document.querySelector('.Btn');
    const parent = document.querySelector('.parent1');
    btn.addEventListener('click', () => {
      [...parent.children].forEach(child => child.style.display = 'inline-block');
    });
  </script>
</body>
</html>

Kết quả

3 ô vuông màu đỏ, hồng, xanh hiện ra cạnh nhau.

Lưu ý: children (Element) vs childNodes (kể text/comment). firstElementChild, lastElementChild lấy nhanh child đầu/cuối.