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
Share:
32,912
eastboundr
Author by

eastboundr

Truth Sets You Free.

Updated on July 09, 2022

Comments

  • eastboundr
    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
    Smamatti over 12 years
    You actually have linebreaks in the div, too. SO it's better to access the specific element and trim like ShankarSangoli did.
  • eastboundr
    eastboundr over 12 years
    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
    eastboundr over 12 years
    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.
  • Nicholas Decker
    Nicholas Decker about 11 years
    I appreciate the simplicity of this
  • Ben
    Ben over 10 years
    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)
  • Marc B
    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
    Ben over 10 years
    My bad, it actually doesn't count tags. But it does count all the script inside the div. So, i take my words.
  • Marc B
    Marc B over 10 years
    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').