Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 317
eastboundr Avatar asked Nov 23 '11 19:11

eastboundr


People also ask

How do you count text in JavaScript?

In JavaScript, we can count the string occurrence in a string by counting the number of times the string present in the string. JavaScript provides a function match(), which is used to generate all the occurrences of a string in an array.

How do I count the number of elements in HTML?

To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object.


2 Answers

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

should do the trick.

like image 60
Marc B Avatar answered Sep 27 '22 21:09

Marc B


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
like image 37
ShankarSangoli Avatar answered Sep 27 '22 21:09

ShankarSangoli