Reputation: 1877
Hi I want to be able to count the number of displayed characters in a Div with javascript/jquery. For example
<div id=mydiv>
<p>This is my div!</p>
</div>
I want to get the number 15 since that's how many chars in the div including spaces.
Thanks!
Upvotes: 20
Views: 36289
Reputation: 1574
In case you are searching for a Vanilla Javascript solution.
Here is one with whitespace:
document.querySelectorAll('#mydiv')[0].textContent.length
Here is one without whitespace:
document.querySelectorAll('#mydiv')[0].textContent.replace(/\s/g,'').length
Upvotes: 3
Reputation: 69905
Try this. I am trimming to avoid any white spaces in the content start or end.
$.trim($("#mydiv").text()).length
If you want to keep spaces also in the count then don't trim it just use this.
$("#mydiv").text().length
Upvotes: 12