How to count the number of characters in a DIV with javascript
32,912
Solution 1
$('#mydiv').text().length
should do the trick.
Solution 2
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
Solution 3
Sample
http://jsfiddle.net/TrMRB/
$("#mydiv p").text().length;
Solution 4
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
Comments
-
eastboundr almost 2 years
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!
-
Smamatti over 12 yearsYou actually have linebreaks in the div, too. SO it's better to access the specific element and
trim
like ShankarSangoli did. -
eastboundr over 12 yearsThanks 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 over 12 yearsthanks, 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.
-
Nicholas Decker about 11 yearsI appreciate the simplicity of this
-
Ben over 10 yearsthis 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)
-
Marc B over 10 years@SilentCave: no, it doesn't count tags. that's why there's the
.text()
call. e.g.<p><b>foo</b></p>
and doing$('p').text().length
will give you 3, not 10, because the<b></b>
is NOT counted. -
Ben over 10 yearsMy bad, it actually doesn't count tags. But it does count all the script inside the div. So, i take my words.
-
Marc B over 10 yearsThat'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
oralert('hello world')
.