Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of all elements that resides at the clicked point?

On user click I would like to get a list of all elements that resides at the clicked point.

For example, if user clicks on Hello here:

<div><span>Hello<span></div>

I would like to get the following list:

  • <span> element
  • <div> element
  • <body> element
  • <html> element

What would be the easiest method to get these elements ?

like image 492
Misha Moroshko Avatar asked Sep 17 '10 12:09

Misha Moroshko


2 Answers

EDIT: Based on clarification, I think this is what you mean:

EDIT: As pointed out by @Misha, outerWidth() and outerHeight() should be used in lieu of width() and height() in order to get an accurate range.

Also, if there's nothing to prevent event bubbling on the page, then the click should be placed on the document as it will be much more efficient. Even if some other click handler prevents bubbling, you should still have the click on the document, and just handle it separately from those handler that prevent bubbling.

Example: http://jsfiddle.net/57bVR/3/

$(document).click(function(e) {
    var clickX = e.pageX
        ,clickY = e.pageY
        ,list
        ,$list
        ,offset
        ,range
        ,$body = $('body').parents().andSelf();

    $list = $('body *').filter(function() {
        offset = $(this).offset();
        range = {
            x: [ offset.left,
                offset.left + $(this).outerWidth() ],
            y: [ offset.top,
                offset.top + $(this).outerHeight() ]
        };
        return (clickX >= range.x[0] && clickX <= range.x[1]) && (clickY >= range.y[0] && clickY <= range.y[1])
    });

    $list = $list.add($body);

    list = $list.map(function() {
        return this.nodeName + ' ' + this.className
    }).get();
    alert(list);
    return false;
});​

Original answer:

This will give you an Array of the tag names including the span. Couldn't quite tell if this is what you wanted.

It uses .parents() along with .andSelf() to get the elements, then uses .map() with .get() to create the Array.

Example: http://jsfiddle.net/9cFTG/

var list;

$('span').click(function() {
    list = $(this).parents().andSelf().map(function() {
        return this.nodeName;
    }).get();
    alert(list);
});​

If you just wanted the elements, not the tag names, get rid of .map() and .get().

Or if you wanted to join the Array into a String using some sort of separator, just add .join(" ") after .get(), placing your separator inside the quotes.

like image 180
user113716 Avatar answered Oct 19 '22 19:10

user113716


In the near future this should be possible:

$(document).click(function(e) {
    var family = this.elementsFromPoint(e.pageX, e.pageY);
    $(family).each( function () {
            console.log(child);
    });
});

Update 2019
Currently in editors draft:
Elements from point

like image 11
Persijn Avatar answered Oct 19 '22 18:10

Persijn