JQuery ID Number Range

I am trying to write a jQuery script that will add a class to enumerate elements within a specific range of identifiers. I use numbers in my ID and want to set up a range of identifiers.

<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 express elements 16 through 19. How do I do this?

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

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

+3
source share
4 answers

this is what jquery is . The slice () method was developed for.

jQuery, DOM,.slice() jQuery . ; , .

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

: http://jsfiddle.net/VpNnJ/

: gt() : lt()

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

: http://jsfiddle.net/cLjXE/

+3
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';
});

, , , ,

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

, :

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

, @matchew , .slice():

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

jsFiddle.

+3

( )
jQuery.

:

$.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');

Help:
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

0
source

All Articles