MeltingDog
MeltingDog

Reputation: 15488

Jquery .text().length counting element's code as well as characters?

I want to detect the amount of characters in a div and do something if there is less then five:

var n = $("#mydiv").text().length;
if (n < 5){
      //do something
  }

But 'n' seems to be counting the code used for the div it self:

<div id="mydiv">

</div>

So even if there are no characters within the div: n = 23.

Does anyone know a way to adjust this to only count characters within the div itself?

Upvotes: 0

Views: 1236

Answers (2)

Jai
Jai

Reputation: 74738

do the trim:

var n = $("#mydiv").text().trim().length;

There are new line characters even your div is empty, so that is getting in count.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388436

Trim the text to exclude the leading and trailing spaces in the text

var n = $.trim($("#mydiv").text()).length; //use String.trim() if you want to support IE9+

Demo: Fiddle

Upvotes: 3

Related Questions