Node.textContent

来源:互联网 发布:sass for mac打开很慢 编辑:程序博客网 时间:2024/05/16 18:48
Node.textContent

1.Summary
获取某个结点及其后代的文本内容或设置结点的文本内容.

2.Syntax

var text = element.textContent;
element.textContent = "this is some sample text";

3.说明
1).若元素为document,或文档类型,或注记,则textContent返回null.为获取整个文档的所有文本和CDATA数据,请使用document.documentElement.textContent

2).若某个结点为CDATA片段,注释,处理指令或文本结点,textContent返回该结点内的文本即该结点的nodeValue属性值.

3).对于其它类型结点,textContent返回其每个子结点的textContent属性值,包括注释,处理指令结点.

4).如果该结点没有子结点,则返回空字符串.设置某个结点的textContent属性值将会删除它的所有子结点并用一个文本结点替代.

4.Differences from innerText

IE推荐使用element.innerText替换element.textContent.(原因大家都知道)

注:textContent返回所有元素的内容,包括<script>和<style>元素,但innerText不包含.innerText也知道根据样式不返回隐藏元素的文本,但textContent会返回.由于innerText知道CSS绘制,所以设置innerText会导致重绘,但textContent不会.
Note that while 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.
As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not.

5.Differences from innerHTML

innerHTML返回HTML字符串.一般会使用innerHTML来快速获取某个元素的文本内容或写文本到元素中.但是应尽量使用innerText替代,不仅涉及到性能问题,还可以避免XSS.
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. innerText should be used instead. Since the text is not processed it's likely to have better performance. Moreover, this avoids an XSS vector attack.

原文:
https://developer.mozilla.org/en/DOM/Node.textContent