Home  >  Article  >  Web Front-end  >  Solution to the problem that Mozilla browser does not support innerText_javascript skills

Solution to the problem that Mozilla browser does not support innerText_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:12:29856browse

For example:

Hello , world!


We use the code: alert((document.getElementById("test")).innerText)

In IE and Chrome, we can get "Hello, world!", but in Firefox, we get "undefined". The original reason is that firefox does not support the innerText attribute of the element. 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 a nodeValue attribute, and all browsers support it. We can try to use this method to read the text within an HTML element.
The following original code just solves this problem:

Copy the code The code is as follows:

function getText(e) {
//If the browser supports the innerText attribute of the element, it will return this attribute directly
if(e.innerText) { return e.innerText; }
//Not supported innerText attribute, use the following method to process
var t = "";

//If an element object is passed in, continue to access its child elements
e = e.childNodes || e;

//Traverse all sub-elements of the sub-element
for(var i=0; i//If it is a text element, accumulate to characters 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 take a look at the following DOM structure:

Hello , world!


Then, we Use:
alert(getText(document.getElementById("test"));
You can get "Hello, world!" in IE, Chrome, and Firefox.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn