aixecador
aixecador

Reputation: 876

Length of a `p`, change `class` in parent `div` jQuery

I am trying to adapt the height of a parent div depending on the text length of its child p.descr. I do that by applying a class, which in turn has different height in CSS. Find below jQuery code:

$(document).ready(function(){  
  $('p.descr').each(function(){
        if($(this).text().length < 90){
          $(this).parent().addClass('bigP90');
        } if($(this).text().length [90,180]) {
          $(this).parent().addClass('bigP180');
        } if($(this).text().length [181,270]) {
          $(this).parent().addClass('bigP270');
        } if($(this).text().length [271,360]) {
          $(this).parent().addClass('bigP360');
        } if($(this).text().length > 360) {
          $(this).parent().addClass('bigP450');
        }
  });
});

The problem is that class bigP90 and bigP450 get applied and work fine, but not the ones in the middle. This means there is something wrong with the syntax but can't figure out what. Thanks.

Upvotes: 0

Views: 51

Answers (1)

Barmar
Barmar

Reputation: 781779

length [90,180] doesn't test whether the length is between 90 and 180. Square brackets are for accessing array elements or object properties, so this treats length as an array and tries to access the 180'th element of the array.

There's no short syntax for testing a range in Javascript. You simply test if it's above the lower limit and also below the upper limit, e.g.

if (val >= 90 && val < 180)

But since you've already tested the lower limit with the previous if, you can use else if to just test the next upper limit, the lower limit test would be redundant.

$(document).ready(function() {
  $('p.descr').each(function() {
    var len = $(this).text().length;
    var parent = $(this).parent();
    if (len < 90) {
      parent.addClass('bigP90');
    }
    else if (len < 180) {
      parent.addClass('bigP180');
    }
    else if (len < 270) {
      parent.addClass('bigP270');
    }
    else if (len < 360) {
      parent.addClass('bigP360');
    }
    else {
      parent.addClass('bigP450');
    }
  });
});

Upvotes: 2

Related Questions