JavaScript textContent vs innerText vs innerHTML Guide
textContent, innerText, and innerHTML are properties used to access and set the content of an element.
- textContent: textContent returns all the text content of an element, including the text within its child elements. It can be used to retrieve or set the text content of an element.
Example:
I need to study for my exam tomorrow.
I have to prepare for my exam that is taking place tomorrow.
let element = document.getElementById("example");
console.log(element.textContent); // 获取元素的文本内容
element.textContent = "这是新的文本内容"; // 设置元素的文本内容
- InnerText returns the visible text content of an element, excluding hidden elements and text styles. It can be used to retrieve or set the visible text content of an element.
Example:
“I have a lot of homework to do tonight.” -> “I have a large amount of homework that needs to be completed tonight.”
let element = document.getElementById("example");
console.log(element.innerText); // 获取元素的可见文本内容
element.innerText = "这是新的可见文本内容"; // 设置元素的可见文本内容
- innerHTML is used to return all of the HTML content of an element, including tags and text. It can be used to retrieve or update the HTML content of an element.
Example:
他们去了海边散步。
They went for a walk by the seaside.
let element = document.getElementById("example");
console.log(element.innerHTML); // 获取元素的HTML内容
element.innerHTML = "<p>这是新的HTML内容</p>"; // 设置元素的HTML内容
In summary, textContent is used to get and set the text content of an element, innerText is used to get and set the visible text content of an element, and innerHTML is used to get and set the HTML content of an element. Choose the appropriate property to manipulate the content of elements as needed.