0

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.

1
  • do you mean "data-num attribute" instead of "data-num argument" ? Commented Aug 8, 2012 at 21:12

2 Answers 2

2

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

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 jQuery
@user1559555: Check my edit, you can try something like that. Or you can use a .each after the .filter to increment the values.
1
$('[data-num]').filter(function(){
    if (parseInt(this.getAttribute('data-num')) >= 251){
        return true;
    }
    else{
        return false;
    }
})

1 Comment

+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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.