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()
?
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');
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With