0

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 & Chrome,

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??

Community
  • 1
  • 1
dexter
  • 1,207
  • 10
  • 26
  • 41
  • 1
    I have no problem executing this code on Mozilla. How exactly do you use it? – Igor Zinov'yev Dec 23 '09 at 08:54
  • i am working on asp.net and in my aspx page document.ready function calls WCF service and that returns result in callback function ,and that callback function generates html. all above code comes in callback function (javascript function) which creates html to disply on aspx page – dexter Dec 23 '09 at 09:05
  • This doesn't need to be a separate question, please keep it in the original. Code works for me FWIW. – bobince Dec 23 '09 at 13:44

2 Answers2

3

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;
 }
ACP
  • 34,682
  • 100
  • 231
  • 371
0

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;    
}
ifti
  • 649
  • 1
  • 11
  • 25