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.