I’ve read on different forums questions of people asking how they can make the innerText property work in Firefox. Many have suggested to use the innerHTML property instead, but that would not be useful because, obviously, the HTML tags would be either rendered or displayed (an example of the latter would be if we want such text to be displayed in a textarea or text field) giving undesired effects.
Well, in short, Firefox does not support the innerText property. Instead, it supports the textContent property.
So, you could check for the browser’s feature support to use the correct property accordingly (this is better than sniffing ;))
Example (updated):
if(document.all){
document.getElementById('element').innerText = "my text";
} else{
document.getElementById('element').textContent = "my text";
}
That’s it. Hope it helps
在Firefox下与innerText等效的属性:textContent
在IE和Opear下,DOM对象支持innerText属性,可以很方便的去除HTML标签。
但在Firefox不支持该属性,好在FF下的DOM对象支持textContent,该属性与innerText等效。
演示实例:
- <p >http://www.cnlei.com</a>.</p>
- <script type="text/javascript">
- function getInnerText(obj){
- return document.all?obj.innerText:obj.textContent;
- }
- var str = getInnerText(document.getElementById("TestObj"));
- alert(str);
- </script>
为Firefox下的DOM对象增加innerText属性:
- <script type="text/javascript">
- var lBrowser = {};
- lBrowser.agt = navigator.userAgent.toLowerCase();
- lBrowser.isW3C = document.getElementById ? true:false;
- lBrowser.isIE = ((lBrowser.agt.indexOf("msie") != -1) && (lBrowser.agt.indexOf("opera") == -1) && (lBrowser.agt.indexOf("omniweb") == -1));
- lBrowser.isNS6 = lBrowser.isW3C && (navigator.appName=="Netscape") ;
- lBrowser.isOpera = lBrowser.agt.indexOf("opera") != -1;
- lBrowser.isGecko = lBrowser.agt.indexOf("gecko") != -1;
- lBrowser.ieTrueBody =function (){
- return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
- };
- //为Firefox下的DOM对象增加innerText属性
- if(lBrowser.isNS6){ //firefox innerText define
- HTMLElement.prototype.__defineGetter__( "innerText",
- function(){
- return this.textContent;
- }
- );
- HTMLElement.prototype.__defineSetter__( "innerText",
- function(sText){
- this.textContent=sText;
- }
- );
- }
- alert(lBrowser.isNS6);
- </script>
附录 DOM Reference:
Firefox DOM参考:http://www.mozilla.org/docs/dom/domref/dom_shortTOC.html
IE DOM参考:
http://msdn2.microsoft.com/en-us/library/ms533050.aspx