What would be the correct way to extend the jQuery attributes selector so that it supports Less Than and Greater Than?
I have some elements which contain a custom attribute SequenceNumber holding an integer. (Before anyone starts I cant use the data property (I think?) because this html is determined at runtime and generated serverside)
Either way. What I am looking to achieve is the ability to select a number of elements that contain a SequenceNumber BETWEEN X AND Y.
So basically something like this
$("#divSequenceGrid ul[SequenceNumber=>'1'][SequenceNumber<='10']").each(func);
Obviously I can do this by going
$("#divSequenceGrid ul").each(function (index, value) {
//Push into an array those that fit my criteria
});
But I'm wondering if there is a butter way?
What would be the correct way to extend the jQuery attributes selector so that it supports Less Than and Greater Than?
I have some elements which contain a custom attribute SequenceNumber holding an integer. (Before anyone starts I cant use the data property (I think?) because this html is determined at runtime and generated serverside)
Either way. What I am looking to achieve is the ability to select a number of elements that contain a SequenceNumber BETWEEN X AND Y.
So basically something like this
$("#divSequenceGrid ul[SequenceNumber=>'1'][SequenceNumber<='10']").each(func);
Obviously I can do this by going
$("#divSequenceGrid ul").each(function (index, value) {
//Push into an array those that fit my criteria
});
But I'm wondering if there is a butter way?
Share Improve this question edited Feb 1, 2015 at 16:35 Deduplicator 45.7k7 gold badges72 silver badges123 bronze badges asked Oct 5, 2011 at 5:50 Maxim GershkovichMaxim Gershkovich 47.2k46 gold badges162 silver badges247 bronze badges 1- Could filter possibly serve your needs? api.jquery./filter – Deets McGeets Commented Oct 5, 2011 at 5:54
2 Answers
Reset to default 11Using .filter()
$("#divSequenceGrid ul").filter(function(){
return $(this).attr("sequenceNumber") >=1 && $(this).attr("sequenceNumber") <=10}).css("color", "red");
Here's a demo: http://jsfiddle/jFt9N/3/
You can use jQuery Selector expressions like this
$.extend($.expr[':'], {
sMore: function(e, i, m) { return parseInt($(e).attr('SequenceNumber')) >= m[3]; },
sLess: function(e, i, m) { return parseInt($(e).attr('SequenceNumber')) <= m[3]; }
});
$(function () {
alert($('div:sMore(2):sLess(4)').length);
});