Character counter of an h

Asked

Viewed 377 times

1

I would like to know how many characters it contains within this H2, which in this case ex: <h2 class="h2">Ola Mundo</h2> contains 9 characters.

  • All <H2> goes var contador = $('h2').length and it’s classy like this var contador = $('h2[class*=h2]').length is jquery.

  • Thank you again Sergio !!!!

1 answer

1


In Javascript Strings have a property .length that gives you exactly what you want.

DOM objects have a property innerHTML which gives its contents (or innerText if you want to ignore HTML).

Combine that with a method that will fetch the object from the DOM you get what you want:

var length = document.querySelector('h2.h2').innerHTML.length;

Example: https://jsfiddle.net/ryjjo0dj/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.