Sean
Sean

Reputation: 21

How do I write the number of characters in a div?

I'm trying to display the character count of various divs I have on a page.

I have this:

<div class="myText">Here is some text.</div>
<div class="myText">Here is some more text.</div>

I'd like to display the character count after each one. So the page would look like this:

Here is some text. 18

Here is some more text. 23

I know I can use jQuery:

$('.myText').text().length

combined with

document.write

but I have no idea how (I'm just starting to learn javascript). Also, the divs are generated by our CMS so there are going to be a lot of them and I'd like to get character counts for them all so maybe they each need different class names?

Any help would be appreciated.

Upvotes: 2

Views: 79

Answers (1)

tadeuzagallo
tadeuzagallo

Reputation: 2522

$('.myText').each(function() {
  var $this = $(this);
  $this.append($this.html().length);
});

Upvotes: 1

Related Questions