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()
?
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()
?
4 Answers
Reset to default 9var 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 mon 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');
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/VpNnJ/
you could also bine the :gt() and :lt() selectors as follows
$('li:gt(16):lt(19)').addClass('the-class');
again a live example: http://jsfiddle/cLjXE/
jQuery('li[id^="item-"]').filter(function() {
var number = this.id.replace(/\D+/, '');
return number >= 16 && number <= 19
}).addClass('the-class');
jsFiddle.
(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./2009/06/custom-jquery-selectors.html
http://www.bennadel./blog/1457-How-To-Build-A-Custom-jQuery-Selector.htm