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?
CSS [attribute^="value"] Selector The [attribute^="value"] selector is used to select elements with the specified attribute, whose value starts with the specified value. The following example selects all elements with a class attribute value that starts with "top": Note: The value does not have to be a whole word!
The CSS Attribute Selector is used to select an element with some specific attribute or attribute value. It is an excellent way to style the HTML elements by grouping them based on some specific attributes and the attribute selector will select those elements with similar attributes.
To use this selector, add a pipe character (|) before the equals sign. For example, li[data-years|="1900"] will select list items with a data-years value of “1900-2000”, but not the list item with a data-years value of “1800-1900”. Value ends with: attribute value ends with the selected term.
It matches links with href attributes whose values start with the given string.
Using .filter()
$("#divSequenceGrid ul").filter(function(){
return $(this).attr("sequenceNumber") >=1 && $(this).attr("sequenceNumber") <=10}).css("color", "red");
Here's a demo: http://jsfiddle.net/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);
});
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