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

, the # of characters should be 2, not 19.

I've tried 2 methods which do not work:

  1. str.length
    - This will include

  2. getElementById
    - This will include

I tried as follows:

elem_output = document.getElementById("example_id");

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');
<strong id="test">Hi</strong>

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