0
var x = 50;

I need to select the first card which has offset().left greater than x

$('.card').each(function(){
    if ($(this).offset().left > x) {...}
});

So how to reduce the above to the first element matched?

  • @VinitDivekar How is it different? They want to match the first element with an offset().left > x in an each loop- they simply have to break out the loop when they find the condition matches – chevybow Jul 25 '18 at 20:26
  • @chevybow, no, it is not duplicated. read again the target link, espacially question note and last answer –  Jul 25 '18 at 20:40
  • 1
    Inside your `if`, you do whatever it is you want to do on first element and `return false;`, which will exit the `.each()`. It is a duplicate. – tao Jul 25 '18 at 20:52
  • @AndreiGheorghiu, no, try and you'll see –  Jul 25 '18 at 21:00
  • If you want an expression that returns an element so you do whatever with it afterwards, you can use `filter()`. `each()` **does not return the collection** (or any of its members). It doesn't return anything. It just runs code on the collection. But you can still use `each()` for your purpose. Outside the `each()` you define a variable. Inside the `each()` you place your element inside the variable and `return false;` now you're outside the `each()` and have your (first) element in the variable, to do whatever you want with it. – tao Jul 25 '18 at 21:03

1 Answers1

1

You can do this using jQuery's filter function

Something like

var x=50;
var first=$('.card').filter(()=>{
    return $(this).offset().left>x;
}).first();

should give you the first element matching your requirements.

sbrass
  • 905
  • 7
  • 12
  • `Uncaught TypeError: r.getClientRects is not a function` –  Jul 25 '18 at 21:03
  • That seems like there's a problem somewhere else in your code. Make sure to check that `r` is whichever object you expect it to be, and that it has the `getClientRects` function – sbrass Jul 25 '18 at 21:05
  • Sounds like you're using jQuery 3.x.x with a jQuery UI version below 1.2.0, @puerto. See [this question](https://stackoverflow.com/questions/37914869/jquery-ui-error-f-getclientrects-is-not-a-function). – tao Jul 25 '18 at 21:10
  • there is no jquery ui on my page. jquery is 3.3.1 –  Jul 25 '18 at 21:24