Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find First Element With Data Attribute Greater Than Zero JQuery

I have a list of divs with the class .item-wrap

Currently, I select the first div using the following code

$(".item-wrap:first").trigger( "click" );   

Each .item-wrap has a data-amount attribute.

How can I modify my current code to select the first .item-wrap that has data-amount greater than 0?

like image 213
Belgin Fish Avatar asked Jan 24 '26 09:01

Belgin Fish


2 Answers

Using the filter function, we can restrict our search. To select an element by it's data-attribute, jQuery has a handy data() function.

This may show up multiple results, as in my example. To get the first one, you can use the first method.

$("div").filter(function() {
  return $(this).data("amount") > 0;
}).first().css({"color": "green"});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-amount="-7">On Tuesday I lost 7 dollars gambling</div>
<div data-amount="-3">On Wednesday, I lost 3 dollars gambling</div>
<div data-amount="37">On Thursday, I actually won 37 dollars</div>
<div data-amount="16">I'm on a roll. Won 16 more dollars today</div>

Some Notes

  • If your data-attribute does not consist solely of numbers, this code will not work. This is assuming all of your data-amounts have a value that matches the regular expression: \A\d*\z

  • A string can be compared against a number if the string matched a particular pattern. This is because JavaScript performs automatic type conversion. In this example, it's fairly trivial because we don't have a lot of data. However, if you had many more divs, you might want to do something like +$(this).data("amount") > 0

like image 128
Richard Hamilton Avatar answered Jan 26 '26 23:01

Richard Hamilton


You can use each() to iterate over the elements and exit from loop by using return false;

$('.item-wrap').each(function() {
    if (+$(this).data('amount') > 0) {
        // Do "Hello World" here
        $(this).trigger('click');

        // Breakout
        return false;
    }
});
like image 36
Tushar Avatar answered Jan 26 '26 21:01

Tushar