2

I would like to apply a class to each div with a certain id if that id ends with a even number. Also i want to apply a different class to the ones that end with a odd number. Ideally it would be great if that can be achieved with jquery.

Here is a example. I want to add class "Red" to all divs with id "item1" where the final number is odd. So class "Red" will be applied to item1, item3, item5.

Similarly i want to add class "Green" to all divs with id "item2" where the final number is even. So class "Green" will be applied to item2, item4, item6.

Thanks, any help would be greatly appreciated!

Steve Greatrex
  • 15,789
  • 5
  • 59
  • 73
salmon
  • 43
  • 1
  • 3

4 Answers4

4

Steve's answer looks nice and clean if you meet the prerequisites.

If not, you can loop through them:

$('div').each(function(d) {
  num = Number( /\d+$/.exec( d.attr('id') )[0] );
  if (isNaN(num)) return;
  d.addClass(num % 2 == 0 ? 'even' : 'odd');
});

Or the more jQuery-sh:

$('div')
  .filter(function(d) { return /[02468]$/.test( d.attr('id') ); })
  .addClass('even');
$('div')
  .filter(function(d) { return /[13579]$/.test( d.attr('id') ); })
  .addClass('odd');
Fábio Batista
  • 25,002
  • 3
  • 56
  • 68
0

You could use jquery regular expressions - see this question.

Community
  • 1
  • 1
Herb Caudill
  • 50,043
  • 39
  • 124
  • 173
0
function doStuff(baseId, evenClassName, oddClassName) {
    $('[id^=' + baseId + ']').each(function() {
        var $this = $(this);
        var number = $this.attr('id').replace(baseId, "");
        $this.addClass(number % 2 == 0 ? evenClassName : oddClassName);
    });
}

$(document).ready(function() {
    doStuff("item", "Green", "Red");
});

Note: not tested

As Steve pointed out in the comments you could use :odd and :even jQuery selectors, but if that's the case then why not just use CSS :nth-child pseudo selector:

<div id="mystuff">
    <div id="item1" class="item"></div>
    <div id="item2" class="item"></div>
    <div id="item3" class="item"></div>
</div>

#mystuff .item {
    /* your default and odd styles here */
}
#mystuff .item:nth-child(2n+1) {
    /* your even styles here */
}
roryf
  • 29,592
  • 16
  • 81
  • 103
0
$('[id^=id-start-][id$=0],'
+ '[id^=id-start-][id$=2],'
+ '[id^=id-start-][id$=4],'
+ '[id^=id-start-][id$=6],'
+ '[id^=id-start-][id$=8]').addClass('myClass');
Nathan MacInnes
  • 11,033
  • 4
  • 35
  • 50