Giả sử cho đoạn code HTML sau:

<h1 id="heading" class="heading">This is a heading</h1>

Để lấy ra nội dung của element thì dùng thuộc tính innerText hoặc textContent thông qua element node.

const headingElement = document.getElementById("heading")
 
console.log(headingElement.innerText) // This is a heading
console.log(headingElement.textContent) // This is a heading

Cũng có thể chỉnh sửa nội dung sử dụng setter:

headingElement.innerText = "Heading"
console.log(headingElement.innerText) // Heading

Important

Sự khác biệt giữa innerTexttextContent:

  • innerText lấy ra toàn bộ nội dung của các tag con có trong element mà không quan tâm đến khoảng cách, đúng như những gì được hiển thị trên web và nó là một thuộc tính thuộc về lớp đối tượng Element.
  • textContent trả về nội dung của text node ở trong mô hình DOM và là một thuộc tính của lớp đối tượng của Node (lớp cha của Element). Nếu nội dung của text node bị ẩn trên web, textContent cũng hiển thị ra được.

Ví dụ:

<h1 id="heading" class="heading">
  <span>This is a</span>
  <span>heading</span>
</h1>

So sánh giữa innerTexttextContent:

const headingElement = document.getElementById("heading")
 
console.log(headingElement.innerText) //  This is a heading
console.log(headingElement.textContent)
//
//     This is a
//     heading

Thậm chí nội dung của thẻ <style> hoặc <script> vẫn được textContent hiển thị:

<h1 id="heading" class="heading">
  <span>This is a</span>
  <span>heading</span>
  <style>
    .box {
      width: 200px;
      height: 30px;
    }
  </style>
</h1>
const headingElement = document.getElementById("heading")
 
console.log(headingElement.innerText) // This is a heading
console.log(headingElement.textContent)
//
//    This is a
//    heading
//
//      .box {
//        width: 200px;
//        height: 30px;
//      }
//

Ngoài ra, Nếu dùng tagged template literals, innerText sẽ chuyển những khoảng trắng xuống dòng thành thẻ <br>. Còn textContent chỉ đơn giản là khoảng trắng.