JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

15.5.2 Element Content As Plain Text

15.5.2 Element Content As Plain Text


Sometimes you want to query the content of an element as plain text, or to insert plaintext into a document (without having to escape the angle brackets and ampersands used in HTML markup). The standard way to do this is with the textContent property of Node:

var para = document.getElementsByTagName("p")[0]; // First

in the document var text = para.textContent; // Text is "This is a simple document." para.textContent = "Hello World!"; // Alter paragraph content

The textContentproperty is supported by all current browsers except IE. In IE, you can use the Element property innerText instead. Microsoft introduced innerText in IE4, and it is supported by all current browsers except Firefox.

The textContent and innerText properties are similar enough that you can usually use them interchangeably. Be careful though to distinguish empty elements (the string “” is falsy in JavaScript) from undefined properties:

/**

*With one argument, return the textContent or innerText of the element.*With two arguments, set the textContent or innerText of element to value. */

function textContent(element, value) { var content = element.textContent; // Check if textContent is defined if (value === undefined) { // No value passed, so return current text

if (content !== undefined) return content;

else return element.innerText; } else { // A value was passed, so set text

if (content !== undefined) element.textContent = value; else element.innerText = value; } }

The textContent property is a straightforward concatenation of all Text node descendants of the specified element. innerText does not have a clearly specified behavior, but differs from textContent in a few ways. innerText does not return the content ofelements. It omits extraneous whitespace and attempts to preserve table formatting. Also, innerText is treated as a read-only property for certain table elements such as,, and.


Text inelements

Inlineelements (i.e., those that do not have a src attribute) have a text property that you can use to retrieve their text. The content of aelement is never displayed by the browser, and the HTML parser ignores angle brackets and ampersands within a script. This makes aelement an ideal place to embed arbitrary textual data for use by your application. Simply set the type attribute of the element to some value (such as “text/x-custom-data”) that makes it clear that the script is not executable JavaScript code. If you do this, the JavaScript interpreter will ignore the script, but the element will exist in the document tree and its textproperty will return the data to you.

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/28014.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1