Track ALL clicked elements using JavaScript

I guess you are looking for something like this:


var arrayWithElements = new Array();

function clickListener(e) 
{   
    var clickedElement=(window.event)
                        ? window.event.srcElement
                        : e.target,
        tags=document.getElementsByTagName(clickedElement.tagName);

    for(var i=0;i<tags.length;++i)
    {
      if(tags[i]==clickedElement)
      {
        arrayWithElements.push({tag:clickedElement.tagName,index:i}); 
        console.log(arrayWithElements);
      }    
    }
}

document.onclick = clickListener;

It will store on every click an object that contains the tagName of the element and the index. So you may access this element in another "instance" of this document by using

document.getElementsByTagName(item.tag)[item.index]

(where item is an item of arrayWithElements)

Demo: http://jsfiddle.net/doktormolle/z2wds/


You can use this related question. In other words, a good way to know which element was clicked without adding IDs all over the place is to use jquery's .cssSelectorAsString() method. For example:

function clickListener(e) {
    var clickedElement;
    if(e == null) {
        clickedElement = event.srcElement;
    } else {
        clickedElement = e.target;
    }
    arrayWithElements.push($(clickedElement).cssSelectorAsString()); // <====
    alert(arrayWithElements);
}    

See also: Get unique selector of element in Jquery