eastboundr
eastboundr

Reputation: 1877

How to count the number of characters in a DIV with javascript

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

Answers (4)

Quinn Keaveney
Quinn Keaveney

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

ShankarSangoli
ShankarSangoli

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

Smamatti
Smamatti

Reputation: 3931

Sample
http://jsfiddle.net/TrMRB/

$("#mydiv p").text().length; 

Upvotes: 3

Marc B
Marc B

Reputation: 360662

$('#mydiv').text().length

should do the trick.

Upvotes: 44

Related Questions