qwertymk
qwertymk

Reputation: 35276

How do I select all classes greater than a value

Suppose I have the following:

<div class="d1">.</div><br>
<div class="d2">.</div><br>
<div class="d3">.</div><br>
<div class="d4">.</div><br>
<div class="d5">.</div><br>
<div class="d6">.</div><br>
<div class="d7">.</div><br>
<div class="d8">.</div><br>
<div class="d9">.</div><br>
<div class="d10">.</div><br>

Is there a selector that will grab all divs of, say, d3 through d7?

You can fiddle around with it here

Keep in mind that they may not be in order in the DOM.

Upvotes: 0

Views: 354

Answers (7)

shaneburgess
shaneburgess

Reputation: 15882

You can also try this.

$('*[class^="d"]').each(function() {
    var number = parseInt($(this).attr("class").match(/\d+/));
    if(number >= 3 && number <= 7){
        $(this).html("Match");
    }
});

http://jsfiddle.net/shaneburgess/nc5e8/15/

Upvotes: 2

abhijit
abhijit

Reputation: 1968

use filter and find methods and you may use the gt and lt for your specific search or any regex for making search more specific

Upvotes: 0

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262939

You can use match() to extract the numbers from the class names and filter() to restrict the set of elements to the subset you want:

var divs = $("div").filter(function() {
    var number = parseInt(this.className.match(/\d+/)[0], 10);
    return (number >= 3 && number <= 7);
});

Upvotes: 7

bjornd
bjornd

Reputation: 22943

You can just generate selector: http://jsfiddle.net/nnZ79/

var start = 3, 
    stop = 7,
    selector = [];

for (; start <= stop; start++) {
    selector.push('.d'+start);
}

$(selector.join(',')).css('background', 'red');

Upvotes: 0

shabunc
shabunc

Reputation: 24731

Well, you always can create specific css selector, say:

$(specificSelector("div.d", 10, 20))

where

specificSelector = function(pref, from, to) {
    var cnames = []
    for (var j = from; j < to; j++) {
        cnames.push(pref + String(j))
    }
    return cnames.join(",")
}

Upvotes: 0

Jason Gennaro
Jason Gennaro

Reputation: 34855

This will get the range you want:

 $('div').slice(2,7).css('background','red');

http://jsfiddle.net/jasongennaro/nc5e8/8/

If you just want greater than, you can do this

 $('div:gt(3)').css('background','red');

http://jsfiddle.net/jasongennaro/nc5e8/13/

Upvotes: 0

Marc Uberstein
Marc Uberstein

Reputation: 12541

You can use this:

$(function() {

    var greaterThan = 4;
    var smallerThan = 8;

    $('div').each(function(i, e) {
        if (i > greaterThan && i< smallerThan) $(e).css('background-color', '#ffcc00');
    });

});

Upvotes: 0

Related Questions