Thomas John
Thomas John

Reputation: 1899

Using jQuery to find an element at a particular position?

Is there a method in jQuery to select an element located at a particular position?

For example, can I select the element that is located at left:100 and top:300 in absolute position?

It would be nice if I could select an element located in a range of positions, for example, select the element that is located left: 100 - 150 px top 200 - 280px.

Upvotes: 51

Views: 50815

Answers (2)

jAndy
jAndy

Reputation: 236012

You are looking for the .elementFromPoint() JavaScript/DOM method.

var elem = document.elementFromPoint(100, 100) // x, y

That returns a DOM node, which of course then can be wrapped into a jQuery object:

$(elem).remove(); // for instance

I'm not that aware about the cross-browser compatibility and I would like some guys who know better to edit this post or write a comment about it.

MDN Reference: .elementFromPoint()

Example Link: http://www.jsfiddle.net/YjC6y/22/

Upvotes: 87

Cees Timmerman
Cees Timmerman

Reputation: 19644

Provided you know the exact coordinates relative to the document:

function getElsAt(top, left){
    return $("body")
               .find("*")
               .filter(function() {
                           return $(this).offset().top == top 
                                    && $(this).offset().left == left;
               });
}

The other answer stops at the first overlay.

Upvotes: 13

Related Questions