2
votes

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!

4
Will you always have all item IDs in sequence? If so, you could just use the :odd or :even selectors (described at api.jquery.com/category/selectors)Steve Greatrex
Please take the Java tag off this - this is purely Javascript/JqueryMartijn Verburg
Yes they wil always be in that sequence. Thanks for the selector tip!salmon

4 Answers

4
votes

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');
0
votes

You could use jquery regular expressions - see this question.

0
votes
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 */
}
0
votes
$('[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');