Search code examples
javascriptevent-delegation

Listen for events on certain element at window level - Javascript, no library


I want to listen for events on <p> elements at window or document level as there are too many such elements to attach an onclick event hander for each.

This is what I've got:

window.onload=function()
{
    window.addEventListener('click',onClick,false);
}
function onClick(event)
{
    alert(event.target.nodeName.toString());
}

I need advice on the code above, is it good? And also, how can I check if the clicked element is a <p> element other than checking nodeName? For example, if the <p> element contains a <b> element and that is clicked, the nodeType will be b not p.

Thank you.


Solution

  • I think it is good, and you can perform checking this way

    var e = event.target
    while (e.tagName != 'P')
       if (!(e = e.parentNode))
           return
    alert(e)