Pepe
Pepe

Reputation: 1002

How to run a function for every element with different results?

I found this nice script, by Bitwise Creative, to change the color of a numeric content by the value.

$(function () {
    // Score Color
    var score = parseInt($('em').text().trim());
    var color = 'red';
    if (!isNaN(score)) {
        if (score >= 2) {
            color = 'orange';
        }
        if (score >= 3) {
            color = 'green';
        }
        $('em').css('color', color);
    }
});

My Problem: It change all numeric content with the same color. So if I have more than one numeric content, this script makes no different between the numbers and colors. How can I modify it like the way, that for example every [em] value [/em] becomes his own color?

<em>1</em> --> red
<em>2.5</em> --> orange
<em>3</em> --> green
<em>1.5</em> --> red

aso.

Upvotes: 0

Views: 65

Answers (4)

Jonas Wilms
Jonas Wilms

Reputation: 138257

To easy: just use a loop to iterate over all ems:

$('em').each( function(){
   var score = parseInt( $(this).text().trim() ),
          color = 'red';

   if (!isNaN(score)) return;

   if (score >= 2) {
        color = 'orange';
   }
   if (score >= 3) {
        color = 'green';
   }
    $(this).css('color', color);
});

Upvotes: 0

kharhys
kharhys

Reputation: 257

You could declare an Object to map integer values to corresponding colors.

var couleurs = {
  1: 'red',
  [2.5] : 'orange'
}

so that you can access as

$(this).css('color', couleurs[color]);

Upvotes: 0

Pritamkumar
Pritamkumar

Reputation: 686

if you want that if score is 2.5 then color must be orange then given score must be float number and you can convert string to float number by using parseFloat which can be done by

var score = parseFloat($('em').text().trim());

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

$('em').text() will give you a string containing the combined text of all matched elements.

You need to iterate the em elements and apply the color to them individually

$(function () {
    // Score Color
    $( "em" ).each( function(){
        var score = parseInt($(this).text().trim());
        var color = 'red';
        if (!isNaN(score)) {
            if (score >= 2) {
                color = 'orange';
             }
             if (score >= 3) {
                 color = 'green';
             }
             $(this).css('color', color);
        }
    });
});

Upvotes: 2

Related Questions