Charles Zha Charles Zha - 3 years ago 63
HTML Question

Character count in innerHTML

In html, how to count the real characters shown in a innerHTML?

For example, In

<strong>Hi</strong>
, the # of characters should be 2, not 19.

I've tried 2 methods which do not work:


  1. str.length
    - This will include
    <>
    characters.

  2. getElementById
    - This will include
    <>
    characters:



I tried as follows:

elem_output = document.getElementById("example_id");
elem_output.innerText.length;//1st
elem_output.textContent.length;//2nd

Answer Source

I don't know which element has #example_id in your code, but element.innerText.length should work.

Edit: Other answers suggest the use of textContent instead of innerText. I think that depending on OP's real needs one or the other (or even innerHTML, which appears in question's title) could be suitable. So, I'd suggest to read carefully the differences between those properties in the docs:

Edit 2: OP's question says real characters shown in a innerHTML, so I'd go with innerText since:

innerText is aware of style and will not return the text of hidden elements, whereas textContent will.

var tag = document.getElementById('test');
console.log(tag.innerText.length)
<strong id="test">Hi</strong>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download