20

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!

eastboundr
  • 1,857
  • 8
  • 28
  • 46

4 Answers4

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

should do the trick.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • I appreciate the simplicity of this – Nicholas Decker Apr 18 '13 at 15:53
  • this is wrong, it doesnt just count the displayed text characters, it counts all the text inside div in html like tags and scripts. hoever i could not found any other way, so for this to work everything inside the div has to be a plain text (not to mention this will count whitespaces) – Ben Aug 27 '13 at 23:22
  • 2
    @SilentCave: no, it doesn't count tags. that's why there's the `.text()` call. e.g. `

    foo

    ` and doing `$('p').text().length` will give you 3, not 10, because the `` is NOT counted.
    – Marc B Aug 28 '13 at 14:15
  • 1
    My bad, it actually doesn't count tags. But it does count all the script inside the div. So, i take my words. – Ben Aug 28 '13 at 22:47
  • 1
    That's to be expected. it's not up to the DOM engine to know what KIND of text is inside a tag. text is text, whether it's `hello world` or `alert('hello world')`. – Marc B Aug 29 '13 at 14:38
12

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
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • Thanks worked like a charm! Actually I do want any white spaces as well, since I'm making a "read more" "read less" div, as long as the text expands the div to certain height, I will put the read more button at the end. So white space is OK if it's part of the editor's choice for formatting or style. – eastboundr Nov 23 '11 at 20:13
3

Sample
http://jsfiddle.net/TrMRB/

$("#mydiv p").text().length; 
Smamatti
  • 3,901
  • 3
  • 32
  • 43
  • You actually have linebreaks in the div, too. SO it's better to access the specific element and `trim` like _ShankarSangoli_ did. – Smamatti Nov 23 '11 at 20:05
  • thanks, actually as long as it takes up space, white space is ok since i want the div box to be certain length then put "read more". So actually i'm more worried about some chars that does no take up space. – eastboundr Nov 23 '11 at 20:15
2

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
Quinn Keaveney
  • 1,248
  • 1
  • 17
  • 39