About Mozilla browsers do not support innertext solutions _javascript Tips

Source: Internet
Author: User
Tags gettext
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!"

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.