Among all major browsers, except for Mozilla browsers, almost all support the attribute of one element: innerText. We can quickly get the text inside an element.
for example:
<p ><strong><font color="red">Hello</font> , world!</strong></p>
We use code: alert((("test")).innerText)
In IE and Chrome, "Hello, world!" can be obtained, but in Firefox, "undefined". It was originally the innerText property in firefox that does not support elements. Of course, there are already many good ways to solve this problem on the Internet, such as adding a property (reader) to the HTMLElement prototype.
However, all text nodes have nodeValue attribute and are supported by all browsers. We can try to read text in an HTML element in this way.
The following original code solves this problem:
function getText(e) { //If the browser supports the innerText attribute of the element, then the attribute will be returned directlyif() { return ; } //When the innerText property is not supported, use the following method to handle itvar t = ""; //If the passed in an element object, continue to access its child elementse = || e ; //Transfer all child elements of child elementsfor(var i=0; i<; i++) { //If it is a text element, it will be accumulated into the string t.if(e[i].nodeType == 3) { t += e[i].nodeValue; } //Otherwise, recursively traverse all child nodes of the elementelse { t += getText(e[i].childNodes); } } return t; }
With this function, let's take a look at the following DOM structure:
<p ><strong><font color="red">Hello</font> , world!</strong></p>
Then, we use:
alert(getText(("test"));
"Hello, world!" can be obtained in IE, Chrome, and Firefox!
Let's share another function below
try{ .__defineGetter__ ( "innerText", function () { var anyString = ""; var childS = ; for(var i=0; i<; i++) { if(childS[i].nodeType==1) anyString += childS[i].tagName=="BR" ? '\n' : childS[i].innerText; else if(childS[i].nodeType==3) anyString += childS[i].nodeValue; } return anyString; } ); } catch(e){}
This is the end of this article about the solution to Mozilla browser's not supporting innerText. For more related content that does not support innerText, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!