Node: thuộc tính parentElement

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Thuộc tính chỉ đọc parentElement của giao diện Node trả về phần tử cha Element của nút DOM, hoặc null nếu nút không có cha, hoặc cha của nó không phải là một nút DOM Element. Trong khi đó, Node.parentNode trả về bất kỳ kiểu nút cha nào, bất kể kiểu của nó.

Giá trị

Một Element là phần tử cha của nút hiện tại, hoặc null nếu không có.

Ví dụ

Dùng parentElement

Ví dụ này đặt phần tử cha của node có màu chữ đỏ.

js
if (node.parentElement) {
  node.parentElement.style.color = "red";
}

parentElement là null

parentElement có thể là null nếu nút không có cha (ví dụ vì nó chưa được gắn vào một cây) hoặc cha của nó không phải là một Element. Ngược lại, Node.parentNode luôn trả về nút cha, nút này có thể là một Document hoặc các kiểu nút khác.

html
<!doctype html>
<html lang="vi">
  <body>
    <script>
      const html = document.querySelector("html");
      console.log(html.parentElement); // null
      console.log(html.parentNode); // document
    </script>
  </body>
</html>

Thông số kỹ thuật

Thông số kỹ thuật
DOM
# ref-for-dom-node-parentelement①

Tương thích trình duyệt

Xem thêm