StackOverflowed
StackOverflowed

Reputation: 5975

In jQuery (or Javascript), how do I get the "topmost" element?

I have a list of elements (with class "newsitem"), that are available throughout the page. I want the highest element, that is the element with the lowest "top" value from that class. How do I get in jQuery efficiently, right now I'm working on iterating through the newsitem class, storing the top value and comparing it with the lowest value so far. Is this pretty much the only way to do it or is there an actual method?

Thanks!

PS: This method is the closest to what I'm doing right now: How to get height of the highest children element in javascript/jQuery?

PPS I have a 50% answer rate only because 2 of my questions so far don't have relevant answers.

Upvotes: 3

Views: 2739

Answers (2)

Rezigned
Rezigned

Reputation: 4942

I believe this should work (but i haven't test it yet)

function get_topmost_element(selector) {
    var top = 0,
        el;
    $(selector).each(function(){
        var offset = $(this).offset();
        if (offset.top > top) {
            highest = offset.top;
            el = $(this);
        }
    });

    return el;
}

Usage

get_topmost_element('.newsitem');

Upvotes: 3

Sang Suantak
Sang Suantak

Reputation: 5265

I guess $(".newsitem:first") should do it.

Upvotes: 0

Related Questions