jQuery: Selecting all elements where attribute is greater than a value
Asked Answered
M

4

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']")
Mendes answered 10/4, 2010 at 14:11 Comment(1)
If you are looking for elements with attributes greater than zero, you can use [attribute!=0]Tears
A
113

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

.filter(function() {
  return $(this).attr("attrName") > "someValue";
})
Ahvenanmaa answered 10/4, 2010 at 14:14 Comment(0)
E
30

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

$("selector").filter(function() {
    return parseInt($(this).attr("my-attr")) > 123;
});
En answered 10/4, 2017 at 19:40 Comment(1)
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).Ajaajaccio
P
29

The solution is jQuery.filter():

$("selector").filter(function() {
    return  $(this).attr("my-attr") > 123;
});
Pula answered 10/4, 2010 at 14:18 Comment(0)
B
0

For ES6 arrow function

$("selector").filter((index, el) => {
    return parseInt($(el).attr("attrName")) > 123;
});
Bohannan answered 5/3, 2021 at 6:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.