views:

39

answers:

3

ok say we have

<span class="foo">7</span>
<span class="foo">2</span>
<span class="foo">9</span>

and want to apply a css class of 'highest' to 'span.foo'.text > 7 and css class of medium to values > 4 and <= 7 and css class of lowest to <= 4

example of desired result:

<span class="foo medium">7</span>
<span class="foo lowest">2</span>
<span class="foo highest">9</span>

Is this a find and filter situation? I'm sure it's common, but I can't seem to find the best way to write it. Thanks

+4  A: 

You could do it with find/filter. It would be easier to do it with each:

$('span.foo').each(function(){
    var $this = $(this),
        val = parseInt($this.html(),10);

    if (val > 7) {
        $this.addClass('highest');
    } else if (val <= 4) {
        $this.addClass('lowest');
    } else {
        $this.addClass('medium');
    }
});
lonesomeday
You should add a 2nd parameter of 10 to parseInt() https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt
yc
You're right, I should.
lonesomeday
+5  A: 
$("span.foo").each(function(){
  var num = parseInt(this.innerHTML, 10);
  if (num > 7)
    this.className += " highest"; 
  else if (num <= 4)
    this.className += " lowest"; 
  else
    this.className += " medium"; 
});
galambalazs
+1 This is more efficient than mine, because it doesn't create new jQuery objects. I prefer mine though as an SO answer... `;-)` I corrected your typo in the second conditional.
lonesomeday
well, thanks man :)
galambalazs
+1  A: 
$(".foo").each(function()
               {
               var layer=$(this);
               var val=parseInt(layer.text());

                if(val>7)layer.addClass("highest")
                    else
                if(val>4 && val<=7)layer.addClass("medium");
                   else {
                       layer.addClass("lowest");
                   }                  
               });

Here you have it: http://jsfiddle.net/dactivo/n6GvJ/

If you prefer with filter even if it is less efficient:

$('.foo').filter(function(index) {
  return parseInt($(this).text())>7
      }).addClass("highest");

$('.foo').filter(function(index) {
  return (parseInt($(this).text())>4 && parseInt($(this).text())<=7)
}).addClass("medium");

$('.foo').filter(function(index) {
  return parseInt($(this).text())<=4
}).addClass("lowest");

Like here: http://jsfiddle.net/dactivo/5tGsj/

netadictos
I think you are missing a parseInt() for the number. Adding that is the way I would do it ;)
Darkxes
It's true, added, thx.
netadictos