Take the 2-minute tour ×

Background: I'm currently writing a greasemonkey script that embeds/modifies a specific page's html. The page is setup with 3 nested divs. Of those 3 divs, I can only add an event listener to the outer most div(This is due to other events and the such already added to the elements). With the inner most div, links are added via AJAX/COMET. As with the inner divs, I can not add event handlers to these links due to the page's current event handlings.

What I need: When a link in the inner most div is clicked, the event will bubble up to the outer most div. From the outer most div, is there a way 1: to tell if it was a link clicked in the inner most div, and if so, 2: how to get that link's href

Please no jQuery solutions. It seems a bit over doing it sense this is the only javascript that will be embedded into the page

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

I would just use a simple cross-browser event listener and the event.target (or event.srcElement in IE), like so:

var addEvent = function (el, ev, fn) {
    if (el.addEventListener) {
        el.addEventListener(ev, fn, false);
    } else if (el.attachEvent) {
        el.attachEvent('on' + ev, fn);
    } else {
        el['on' + ev] = fn;

var outer = document.getElementById('outer');

addEvent(outer, 'click', function(ev){
    ev = ev || window.event;
    var target = ev.target || ev.srcElement;

See demo

share|improve this answer
Beat you to the correction. :P –  mVChr Mar 26 '12 at 2:15
I won't be needing IE support so ev.target is fine. Also, why not just document.getElementById('outer').addEventListner('click',function (ev) {...}); instead of creating a function for it? –  SReject Mar 26 '12 at 2:17
@SReject—usually what is posted here is an example of a solution, you can use it however you like (or not). There are still a lot of browsers in use that support the IE event model (not all are IE), not accommodationg such users in a general web page is not a good idea. –  RobG Mar 26 '12 at 2:26
@RobG the part of my reply about IE was to clearify that the mistype about target wasn't really a big deal. I understand the formatting, but was wondering if there was a specific reason(other than crossbrowser support) for the function. I apologize if I came off as ignorant :) –  SReject Mar 26 '12 at 2:32
@SReject—not at all, there was no context for your statement is all. You never know where code will end up so a bit of cross-browser support never goes astray. :-) –  RobG Mar 26 '12 at 6:02
add comment

Your Answer


