开发者

innerText gives error in mozilla firefox (count words and character of html)

I want to count number of words & number of characters in html text (TEMP),

and while doing that i want to skip HTML tags and html keywords (ex.  )

suppose i am getting HTML text in my JavaScript function as

var TEMP= result.data;  

// where result.data='<p>BODY&nbsp;Article By Archie(Used By Story Tool)</p>';

i have done this:

var e = document.createElement("span");
        e.innerHTML = TEMP;
        var text = e.innerText;
        var characterCount = text.length;                    
        var wordCount = text.match(/\b\w/g).length;

works in Internet Explorer & Chr开发者_StackOverflowome,

but this code doesn't work in mozilla firefox as above code has .innerText property which is not supported by FireFox so i have also tried o.k.w' s code but didn't work in mozilla

o.k.w's code

function getCharCount(str){
    var d = document.createElement("div");
    d.innerHTML = str;
    if(d.innerText) //for IE and others
        alert(d.innerText.length);
    else //for FF
        alert(d.textContent.length);
}

pls help

and important this should work on all (IE,Chrome,mozilla firefox )browser.

can we detect browser (ch, IE, FF)and change code accordingly.?

is there any other way to count words and characters to avoid this issue??


Hai elcon ,

You can use "textContent" in mozilla which is equivalent to "innerText" in IE.

function getInnerText(o)
 {
   return o.textContent ? o.textContent : o.innerText;
 }


if you want to make it browser independent use this code

var field = document.getElementById(id);  // where u want to use innertext

if(field != null)
{           
        if(navigator.appName == "Netscape") // appName for both FireFox and Chrome its is "Netscape" i checked it with different version.

            field.textContent = value;

        else // for For IE v 8 i checked  .textContent is not supported by IE for me it was not working. 

            field.innerText = value;    
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜