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!

4 Answers 4

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

should do the trick.

Sign up to request clarification or add additional context in comments.

5 Comments

I appreciate the simplicity of this
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)
@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.
My bad, it actually doesn't count tags. But it does count all the script inside the div. So, i take my words.
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').
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

1 Comment

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.
3

Sample
http://jsfiddle.net/TrMRB/

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

2 Comments

You actually have linebreaks in the div, too. SO it's better to access the specific element and trim like ShankarSangoli did.
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.
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.