var myElement = document.getElementById('anyElementId');
var myText = (myElement.innerText || myElement.textContent);
本文详细介绍了textContent属性的功能,包括获取和设置节点及其后代的文本内容。与innerText和innerHTML的区别在于其处理方式不同,如不受样式影响且不会触发页面重排。通过示例展示了如何使用textContent来读取或修改DOM元素中的文本。
Gets or sets the text content of a node and its descendents.
var text = element.textContent;
element.textContent = "this is some sample text";
textContent returns null if the element is a document, a document type, or a notation. To grab all of the text and CDATA data for the whole document, one could use document.documentElement.textContent.textContent returns the text inside this node (the nodeValue).textContent returns the concatenation of the textContentattribute value of every child node, excluding comments and processing instruction nodes. This is an empty string if the node has no children.innerText Internet Explorer introduced element.innerText. The intention is pretty much the same with a couple of differences:
textContent gets the content of all elements, including <script>and <style> elements, the mostly equivalent IE-specific property, innerText, does not.innerText is also aware of style and will not return the text of hidden elements, whereas textContent will.innerText is aware of CSS styling, it will trigger a reflow, whereastextContent will not.innerHTML innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Since the text is not processed it's likely to have better performance. Moreover, this avoids an XSS vector attack.
// Given the following HTML fragment:
// <div id="divA">This is <span>some</span> text</div>
// Get the text content:
var text = document.getElementById("divA").textContent;
// |text| is set to "This is some text".
// Set the text content:
document.getElementById("divA").textContent = "This is some text";
// The HTML for divA is now:
// <div id="divA">This is some text</div>
3045

被折叠的 条评论
为什么被折叠?