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:
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.