77

I know that to filter an element with an atttribute called attrName which has value attrValue I do:

filter("[attrName='attrValue']")

but looking at the docs http://api.jquery.com/category/selectors/ I can't see an option to select all elements s.t. attrName>attrValue

Will this work

   filter("[attrName>'attrValue']")
Ankur
  • 50,282
  • 110
  • 242
  • 312
  • 1
    If you are looking for elements with attributes greater than zero, you can use `[attribute!=0]` – Damien Jun 30 '16 at 05:42

4 Answers4

113

You can do this using the function overload of .filter(), like this:

.filter(function() {
  return $(this).attr("attrName") > "someValue";
})
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
29

The solution is jQuery.filter():

$("selector").filter(function() {
    return  $(this).attr("my-attr") > 123;
});
Crozin
  • 43,890
  • 13
  • 88
  • 135
29

Be careful, if you are playing with integers make sure you are using parseInt().

$("selector").filter(function() {
    return parseInt($(this).attr("my-attr")) > 123;
});
Julien Le Coupanec
  • 7,742
  • 9
  • 53
  • 67
  • 7
    Agreed! Some users may see that "3" > "1" is true and think that they don't need to parse the string to an integer before comparing. This works because the ASCII value of "3" is higher than the ASCII value for "1". But things go south when you are comparing values with more than one digit (e.g. "33" > "4" is false while 33>4 is true). – Arthur Hebert-Ryan Jul 16 '18 at 18:12
0

For ES6 arrow function

$("selector").filter((index, el) => {
    return parseInt($(el).attr("attrName")) > 123;
});
Fangxing
  • 5,716
  • 2
  • 49
  • 53