Like what:
<p id= "test" ><strong><font color= "Red" >Hello</font>, world!</strong></p>
We use code: Alert ((document.getElementById ("Test")). innertext)
In IE, chrome, can get "Hello, world!", but in Firefox, but get "undefined". The original is that Firefox does not support elements of the innertext this attribute. Of course, there are many good ways to solve this problem on the web, such as adding a property (reader) to the HtmlElement prototype.
However, all text nodes have nodevalue attributes, and all browsers are supported. We can try to read the text within an HTML element in this way.
The following source code, just solves the problem:
Copy Code code as follows:
function GetText (e) {
If the browser supports the InnerText property of the element, it returns the property directly
if (e.innertext) {return e.innertext;}
When innertext properties are not supported, the following methods are used to handle
var t = "";
If an element object is passed in, it continues to access its child elements
E = E.childnodes | | E
Traversing all child elements of a child element
for (var i=0; i<e.length; i++) {
If it is a text element, it is added to the string T.
if (E[i].nodetype = = 3) {T + = E[i].nodevalue;}
Otherwise recursively traverses all the child nodes of the element
else {T + + getText (e[i].childnodes);}
}
return t;
}
With this function, let's take a look at the following DOM structure:
<p id= "test" ><strong><font color= "Red" >Hello</font>, world!</strong></p>
Then, we use:
Alert (GetText ("Test") (document.getElementById);
In IE, Chrome, Firefox can get "Hello, world!"