Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending attributes selector with Less Than & Greater Than in jQuery

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?

like image 301
Maxim Gershkovich Avatar asked Oct 05 '11 05:10

Maxim Gershkovich


People also ask

How do I use attribute selector?

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!

What are attribute selectors?

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.

How do I style a data attribute in CSS?

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.

What does the CSS selector a href $= org select?

It matches links with href attributes whose values start with the given string.


2 Answers

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/

like image 188
Uku Loskit Avatar answered Oct 27 '22 22:10

Uku Loskit


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);
});
like image 32
verybadbug Avatar answered Oct 27 '22 22:10

verybadbug