Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`else if` is never executed; only the preceding `if` is executed

I have a function which runs through some <div>s, and inside each <div> it counts the amount of children. Then, based on the amount of children (var length), it does something.

$('.member-type').each(function() {
  var length = $(this).children('.views-row').length;
  
  if (length >= 2) {
    console.log('equal to or more than two');
  }
  else if (length > 5) {
    console.log('more than five');
  }
  else {
    console.log('single item');
  }
});

The first if statement works and the else statement works. But for some reason, the else if statement doesn’t work, even when length is higher than 5 (I checked in the console log).

Does anyone know what I’m doing wrong?

like image 207
Ruud Schroën Avatar asked Dec 09 '22 10:12

Ruud Schroën


1 Answers

When the length is greater than 2, it is always greater than 5, so it will always go in the first if statement block. Change the condition in the first if, so that the else part can be executed:

if (length >= 2 && length <= 5) {
  console.log('more than two and less than five');
}
else if (length > 5) {
  console.log('more than five');
}
else {
  console.log('single item');
}
like image 51
Adil Avatar answered Dec 11 '22 08:12

Adil