Get the top element in jQuery
javascript, jquery
Solution
Just iterate through each of the elements:
var $failed = $('.failed');
var top = null; // current "smallest" value
var found = null; // current "topmost" element
$failed.each(function() {
var $this = $(this);
var cur = $this.offset().top;
if (top === null || cur < top) {
found = this;
top = cur;
}
});
Alternative, if you don't actually care which element it is, but just want the scroll position:
var tops = $failed.map(function() {
return $(this).offset().top;
}).get();
var top = Math.min.apply(null, tops);
NB: code corrected to use `.offset` instead of `.scrollTop`
Problem
I've built advanced validation plugin which shows the errors in a specific way. However , when a user input is not valid , I scroll the page to the first element that has failed in validation. this is how it looks : So where is the problem ? I've bolded the `TD's` in black. So you can see that `Currency textbox` is on the first TD where `Owner Name textbox` is on the second TD so `Currency textbox` has validated first , and so , the page scroll to the Currency location and not to the OwnerName text box location . ( as I wish) Question : How can I find the topmost element ( lets assume that all failed elements has `.failed` class - just for simplicity).