Skip to content Skip to sidebar Skip to footer

Apply Different Class To Child DOM Elements Depending On Their Value

This is an extension of this question. We got a structure like the one below, depending on the value of the element with class score we add a class win or lose.

Solution 1:

UPDATE #2

Compare scores inside a .war item and apply classes to .score items

function applyScoreClass() {
  $('.war').each(function(index, elem) {
    var $elem = $(elem);
    var warScores = [];
    $elem.find('.score').each(function(i,el) {
       var txt = $(el).text();
       var num = (txt && txt.length > 0) ? parseInt(txt) : null;
       if (num !== null) {
           warScores.push({
               elem: $(el),
               score: num
           });
       }
    });
    if (warScores.length === 2) {
       if (warScores[0].score > warScores[1].score) {
           warScores[0].elem.addClass('win');
           warScores[1].elem.addClass('lose');
       } else if (warScores[0].score === warScores[1].score) {
           warScores[0].elem.addClass('draw');
           warScores[1].elem.addClass('draw');
       } else if (warScores[0].score < warScores[1].score) {
           warScores[1].elem.addClass('win');
           warScores[0].elem.addClass('lose');
       }
    }
  });
}

applyScoreClass();
.war {
  border: 1px solid #d8d8d8;
}
.win {
  color: green;
}
.draw {
  color: orange;
}
.lose {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="war">
  <div class="team">
    <span class="score">8</span>
  </div>
  <div class="team">
    <span class="score">5</span>
  </div>
</div>
<div class="war">
  <div class="team">
    <span class="score">2</span>
  </div>
  <div class="team">
    <span class="score">4</span>
  </div>
</div>

Solution 2:

Define id value for HTML div/span inside looping scores array declare

var id =document.getElementById('spanId/divId');
id.classList.add('win/lose/draw');

Post a Comment for "Apply Different Class To Child DOM Elements Depending On Their Value"