-1

I have a simple if else statement that will color a number based on it's value.

Can anyone explain why the below always results in red?

$(document).ready(function() {

    // the following will select all elements with class "deltadiff"
    // if the element has a '-', it will assign a 'red' class, else it will assign the 'green class'

    if ($(".deltadiff:contains('-')"))
      $(".deltadiff").addClass('red');
    else $(".deltadiff").addClass('green');
  }

)
.red {
  color: red;
}

.green {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<font class="deltadiff" style="font-size:10px; vertical-align:super;"> -120</font>

<font class="deltadiff" style="font-size:10px; vertical-align:super;"> 120</font>

<font class="deltadiff" style="font-size:10px; vertical-align:super;"> 5</font>

<font class="deltadiff" style="font-size:10px; vertical-align:super;"> -7</font>
ChrisG
  • 8,206
  • 4
  • 20
  • 34
mikelowry
  • 961
  • 2
  • 8
  • 23

1 Answers1

1

if ($(".deltadiff:contains('-')")) only checks for the first element that has deltadiff as classname.

You should loop through all the elements with the same class.

Then, use includes() to check if the innerHTML contains an -.

$(document).ready(function() {

    // For each element with class: 'deltadiff'
    $('.deltadiff').each(function(i, obj) {
      
        // if the element has a '-', it will assign a 'red' class, else it will assign the 'green class'
        if (obj.innerHTML.includes('-')) {
            obj.classList.add("red");
        } else {
            obj.classList.add("green");
        }
    });
});
.red {
  color: red;
}

.green {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<font class="deltadiff" style="font-size:10px; vertical-align:super;"> -120</font>

<font class="deltadiff" style="font-size:10px; vertical-align:super;"> 120</font>

<font class="deltadiff" style="font-size:10px; vertical-align:super;"> 5</font>

<font class="deltadiff" style="font-size:10px; vertical-align:super;"> -7</font>
0stone0
  • 21,605
  • 3
  • 29
  • 49