You can simply attach the event to the onclick handler of the document. There is no need to iterate over each element on the page. Clicks will bubble up to him ...
document.onclick = function(event) { var target = event.target || event.srcElement; alert ( target.innerHTML ); };
However, I recommend using a better method for attaching an event handler than with '=', as it will override any previously defined events that may be critical to the operation of the page.
I used this snippet before to better add events without jQuery ...
var bindEvent = function(elem ,evt,cb) { //see if the addEventListener function exists on the element if ( elem.addEventListener ) { elem.addEventListener(evt,cb,false); //if addEventListener is not present, see if this is an IE browser } else if ( elem.attachEvent ) { //prefix the event type with "on" elem.attachEvent('on' + evt, function(){ /* use call to simulate addEventListener * This will make sure the callback gets the element for "this" * and will ensure the function first argument is the event object */ cb.call(event.srcElement,event); }); } }
You just call ...
bindEvent(document,'click', function(event) { var target = event.target || event.srcElement; alert ( target.innerHTML ); });
source share