For example:
<P id = "test"> <strong> <font color = "red"> Hello </font>, world! </Strong> </p>
Code: alert (document. getElementById ("test"). innerText)
"Hello, world!" can be obtained in IE and Chrome !", However, in Firefox, "undefined" is obtained ". It is originally the innerText attribute that does not support elements in firefox. Of course, there are already many good ways to solve this problem on the network, such as adding an attribute (Reader) to the HTMLElement prototype ).
However, all text nodes have the nodeValue attribute, and all browsers support this attribute. We can use this method to read the text in an HTML element.
The following source code solves this problem:
Copy codeThe Code is as follows:
Function getText (e ){
// If the browser supports the innerText attribute of an element, this attribute is directly returned.
If (e. innerText) {return e. innerText ;}
// If the innerText attribute is not supported, use the following method
Var t = "";
// If an element object is input, access its child element
E = e. childNodes | e;
// Traverse all child elements of a child element
For (var I = 0; I <e. length; I ++ ){
// If it is a text element, it is accumulated into string t.
If (e [I]. nodeType = 3) {t + = e [I]. nodeValue ;}
// Otherwise, recursively traverse all child nodes of the element
Else {t + = getText (e [I]. childNodes );}
}
Return t;
}
With this function, let's look at the following DOM structure:
<P id = "test"> <strong> <font color = "red"> Hello </font>, world! </Strong> </p>
Then, we use:
Alert (getText (document. getElementById ("test "));
"Hello, world!" can be obtained in IE, Chrome, and Firefox! "