Skip to content Skip to sidebar Skip to footer

Why Am I Getting Typeerror: Obj.addeventlistener Is Not A Function?

Here's my code: function addEvent( obj, type, fn ) { if ( obj.attachEvent ) { obj['e'+type+fn] = fn; obj[type+fn] = function(){obj['e'+type+fn]( window.event );} obj.

Solution 1:

document.getElementsByTagName returns a NodeList of DOM elements. Each element has an addEventListener function, but the array doesn't have one.

Loop over it:

function showWinner (){
    var aTags = document.getElementsByTagName("a");
    for (var i=0;i<aTags.length;i++){
        addEvent(aTags[i], 'click', alertWinner);
    }
}

Solution 2:

aTag is an instance of DOMNodeList, not from DOMElement.

You could do this instead:

var aTags = document.getElementsByTagName("a");
var aTag = aTags[0];

But obviously this approach presents a flaw, in that there might be more than one a element returned. You should use a different selector that returns only one element, if possible.

Solution 3:

Not sure why, but I got addEvent is not defined in Firefox. I couldn't even find addEvent() on MDN. I had to use this:

function showWinner (){
    var aTags = document.getElementsByTagName("a");
    for (var i=0;i<aTags.length;i++){
        // addEvent(aTags[i], 'click', alertWinner);
        aTags[i].addEventListener("click", alertWinner);
    }
}

Post a Comment for "Why Am I Getting Typeerror: Obj.addeventlistener Is Not A Function?"