How can I find all elements in the document which have data-num attribute higher or equal to e.g. 251? I would prefer to use jQuery.
2 Answers
You want to use the "has attribute" selector, then filter based on the value.
$('[data-num]').filter(function(){
return parseInt($(this).data('num'), 10) >= 251;
});
DEMO: http://jsfiddle.net/xsvrv/
UPDATE: As per your comment, if you want to update the data-num value, you can do this:
$('[data-num]').filter(function(){
var num = parseInt($(this).data('num'), 10);
if(num >= 251){
$(this).data('num', num+1);
return true;
}
return false;
});
2 Comments
user1559555
one question though... can I somehow increment the data-num of the filtered out elements? I tried
attr('data-add', $(this).data('add')+diff); but it's not working ;) Sorry for such a lame questions, I'm totaly new to jQuerygen_Eric
@user1559555: Check my edit, you can try something like that. Or you can use a
.each after the .filter to increment the values.$('[data-num]').filter(function(){
if (parseInt(this.getAttribute('data-num')) >= 251){
return true;
}
else{
return false;
}
})
1 Comment
jfriend00
+1 I like that you're using
this.getAttribute() instead of $(this).data() since jQuery is not needed here and native JS will be faster. The OP should know that $('[data-num]') is NOT going to be fast because it has to examine every object in the document.