ATLChris
ATLChris

Reputation: 3296

jQuery ID Number Range

I am trying to write a jQuery script that will add a class to list items within a certain ID range. I use numbers in my ID's and want to adjust a range of ID's.

<li id="item-15">Something</li>
<li id="item-16">Something</li>
<li id="item-17">Something</li>
<li id="item-18">Something</li>
<li id="item-19">Something</li>

I want to add a class to say items 16 through 19. How would I do this?

jQuery('li#item-[16-19]).addClass('the-class');

I am not really sure how to do it. Maybe .each()?

Upvotes: 4

Views: 3858

Answers (4)

Matt Ball
Matt Ball

Reputation: 359966

var min = 16, max = 19;

$('li[id^=item-]').addClass(function ()
{
    var i = parseInt(this.id.replace('item-', ''), 10);
    if (i >= min && i <= max) return 'the-class';
});

For the sake of specificity, you should probably qualify the selector with a common parent, such as

$('#some-ul-id > li[id^=item-]').addClass(...);

If the IDs are always sequentially increasing, and zero-indexed, you can simplify:

$('#some-ul-id > li[id^=item-]').addClass(function (i)
{
    if (i >= min && i <= max) return 'the-class';
});

or, as @matchew suggests, use .slice():

$('#some-ul-id > li[id^=item-]').slice(min, max).addClass('the-class');

Upvotes: 9

sv_in
sv_in

Reputation: 14049

(Just an alternate answer)
Go for custom jQuery Selectors.

In your case it 'could' be:

$.expr[':'].customId = function(obj){
  var $this = $(obj);
  var id = $this.attr('id');
  var number = id.replace(/\D+/, '');
  if ((new RegExp(/^item-/).test(id)) && (number > 15 && number < 20)) {
    return true;
  }
  return false;
};

// Usage:
$('a:customId').addClass('the-class');

Reference:
http://jquery-howto.blogspot.com/2009/06/custom-jquery-selectors.html
http://www.bennadel.com/blog/1457-How-To-Build-A-Custom-jQuery-Selector.htm

Upvotes: 0

matchew
matchew

Reputation: 19655

this is what the jquery .slice() method was designed for.

Given a jQuery object that represents a set of DOM elements, the .slice() method constructs a new jQuery object from a subset of the matching elements. The supplied start index identifies the position of one of the elements in the set; if end is omitted, all elements after this one will be included in the result.

so

jQuery('li').slice(17,21).addClass('the-class');
//note Zero Based indexing. Plus it wont include the last element.

live example: http://jsfiddle.net/VpNnJ/

you could also combine the :gt() and :lt() selectors as follows

$('li:gt(16):lt(19)').addClass('the-class');

again a live example: http://jsfiddle.net/cLjXE/

Upvotes: 3

alex
alex

Reputation: 490423

jQuery('li[id^="item-"]').filter(function() {
    var number = this.id.replace(/\D+/, '');
    return number >= 16 && number <= 19
}).addClass('the-class');

jsFiddle.

Upvotes: 3

Related Questions