Solution to Mozilla Browser not support innerText

Source: Internet
Author: User

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! "

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.