0

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>
mikelowry
  • 1,307
  • 4
  • 21
  • 43
  • 2
    You're not iterating over the elements. You have to use [`.each()`](https://api.jquery.com/each/) to handle them individually. You are currently finding at least one with a `-`, then set all of them to red accordingly. –  Mar 15 '21 at 18:34
  • Thanks Chris, sorry new to Javascript, where do i put the .each() – mikelowry Mar 15 '21 at 18:38
  • 1
    You can do this: https://jsfiddle.net/7zw01L9b/ –  Mar 15 '21 at 18:39
  • Thank you @ChrisG! – mikelowry Mar 15 '21 at 18:41

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
  • 34,288
  • 4
  • 39
  • 64