I'm not quite following this. If you have a DOM element (i.e. "this" in your
click function), and you want to do something with it later, simply save a
reference to the element itself. Why do you want to use an index into a
jQuery result array?
Also, in a page with many elements, those "*" selectors are going to be
pretty slow.
Do I understand correctly that you want to identify the topmost parent
element (i.e. a direct child of the BODY) that was clicked? I think I would
do it something like this. There may be a simpler way, but off the top of my
head this should work and would also be very efficient:
$(function() {
// Return element if it is a direct child of the BODY, or the
// topmost parent of element (a direct child of BODY).
function toplevel( element ) {
var $parents = $(element).parents();
var i = $parents.index( document.body );
return i > 0 ? $parents[i-1] : element;
}
$('body').click( function( event ) {
var element = toplevel( event.target );
console.log( element.id, element );
});
});
> I want to get an element by an unique index, then at a later
> time do something to that element, such as add text.
>
> I was trying the following code:
> $(document).ready(function(){
> $("*", document.body).click(function () {
> var index = $("*", document.body).index(this);
> $("*:eq(" + index +")",
> document.body).css("color", "red");
> });
> });
> But when I click, it adds the red text color to all parents
> too. I changed the code too print the index number and it
> appends several index numbers to the element I click and the parents.
>
> I want to get the index number of the top most element that I
> click on. That element may have children or may not.
>
> So, how do I get only the top most element index that I clicked on?
>