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 headingCũng có thể chỉnh sửa nội dung sử dụng setter:
headingElement.innerText = "Heading"
console.log(headingElement.innerText) // HeadingImportant
Sự khác biệt giữa
innerTextvàtextContent:
innerTextlấ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ượngElement.textContenttrả 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ủaNode(lớp cha củaElement). Nếu nội dung của text node bị ẩn trên web,textContentcũ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 innerText và textContent:
const headingElement = document.getElementById("heading")
console.log(headingElement.innerText) // This is a heading
console.log(headingElement.textContent)
//
// This is a
// headingThậ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.