max7
max7

Reputation: 798

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.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener(type, fn, false);
}

function alertWinner(){
    alert("You may be a winner!");
}

function showWinner (){
    var aTag = document.getElementsByTagName("a");
    addEvent(aTag, 'click', alertWinner);
}

showWinner();

Basically, I'm working in the firebug console and trying to get an alert to pop up when any a tag is clicked.

I can't see the problem that results in this not working and giving me the error stated in my questions title (viewed in firebug). Anybody?

Upvotes: 21

Views: 71389

Answers (3)

Sebas
Sebas

Reputation: 21532

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.

Upvotes: 7

Matt Zeunert
Matt Zeunert

Reputation: 16561

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);
    }
}

Upvotes: 37

Jason Lydon
Jason Lydon

Reputation: 7180

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);
    }
}

Upvotes: 4

Related Questions