Best jquery way to search and filter and apply css classes
ok say that we have
<span class="foo">7</span>
<span class="foo">2</span>
<span class="foo">9</span>
and you want to apply the css class' maximum 'to' span.foo'.text> 7 and the css environment class to values> 4 and <= 7 and the css class with a low value <= 4
An example of the desired result:
<span class="foo medium">7</span>
<span class="foo lowest">2</span>
<span class="foo highest">9</span>
Is this a search and filtering situation? I am sure this is a common thing, but I cannot find a better way to write it. Thanks
You can do this with find / filter. It would be easier to do this 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');
}
});
$(".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");
}
});
: http://jsfiddle.net/dactivo/n6GvJ/
, :
$('.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");