George
George

Reputation: 36794

Select numbered element range in jQuery

I imagine this to be quite simple but I can't find out how to do it:

Suppose I have the elements:

<div class="1">Div 1</div>
<div class="2">Div 2</div>
<div class="3">Div 3</div>
<div class="4">Div 4</div>
<div class="5">Div 5</div>
<div class="6">Div 6</div>
<div class="7">Div 7</div>
<div class="8">Div 8</div>

And would like to target the elements within a specific range, to change some CSS attributes. For example:

$(Class > 3 and < 7).css("background","#0077C1");

Obviously the range is going to change. What would be the easiest way of selecting the elements within a given range?

If you think this could be achieved in an easier way than using classes (I'm thinking this is likely) please do mention so.

Upvotes: 2

Views: 328

Answers (4)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

Assuming your question is really about selecting by class and not just by their index, the best would be to combine a starts-with selector and filter.

Let's suppose your classes start with "c" to be valid class names (c1, c2, etc.), then you can select your elements like this :

$('[class^=c]').filter(function(){
   var num = parseInt(this.className.slice(1), 10);
   return num>3 && num<7;
});

Upvotes: 0

Ruslan
Ruslan

Reputation: 10147

You could use .slice() method to select a subset of elements in the array. But this won't use your css class names.

$('div').slice(2, 6).css('background','#0077C1');

Upvotes: 0

asifsid88
asifsid88

Reputation: 4711

<div class="divClass" id="1">Div 1</div>
<div class="divClass" id="2">Div 2</div>
<div class="divClass" id="3">Div 3</div>
<div class="divClass" id="4">Div 4</div>
<div class="divClass" id="5">Div 5</div>
<div class="divClass" id="6">Div 6</div>
<div class="divClass" id="7">Div 7</div>
<div class="divClass" id="8">Div 8</div>

$('.divClass').each(function() {
    var divID = $(this).attr('id');
    if(divID >3 && divID<7)
    {
        // do something
    }
});

Upvotes: 0

Anton
Anton

Reputation: 32591

Try this

$('.2').nextUntil('.8').css('background','#0077C1');

Upvotes: 6

Related Questions