Morlas
Morlas

Reputation: 121

Counting length of div with class separately jQuery

<div class="pam_numbers">18</div>
<div class="pam_numbers">1000</div>
<div class="pam_numbers">1900</div>
<div class="pam_numbers">18</div>

I would like to count number of characters in every div separately to create a conditional if value==2 then...

$(".pam_numbers").text().length

is returning sum of values of every div with class. In this case '12'.

Do I have to add an ID to every div and count from array?

Upvotes: 4

Views: 503

Answers (2)

Adil
Adil

Reputation: 148110

You can use filter() to apply the condition on each element and returning it, if it satisfies your condition.

Live Demo

$(".pam_numbers").filter(function(){    
   if($(this).text().length == 2)
       return $(this);    
});

Edit: As @Mark Schultheiss suggested we can omit if by directly putting condition with return statement.

Live Demo

$(".pam_numbers").filter(function(){      
     return $(this).text().length === 2;
});

Upvotes: 6

cernunnos
cernunnos

Reputation: 2806

You have to treat each div separately, $(".pam_numbers") selects all of them. One approach is to loop through them jQuery style:

$(".pam_numbers").each(function () {
  if ($(this).text().length == 2) {
    // Do stuff
  }
});

Other approach would be to capture the array-like object containing all elements that match the selector and then looping through it traditionally.

var elements = $(".pam_numbers");
for (var i in elements) {
   // check and do stuff
}

Upvotes: 1

Related Questions