Matt_DontKnow
Matt_DontKnow

Reputation: 49

Add events in for loop

I'd like to change the innerText of each <p> to * with a mouseover event.

HTML

<p id="object1">O</p>
<p id="object2">O</p>
<p id="object3">O</p>

I wrote a script, but it affects only the last <p>. What is wrong in my script? I would be grateful for a help.

JavaScript

var nodeList = document.getElementsByTagName('p');

for (var i = 0; i < nodeList.length; i++) {
    var obj = Utility.$(nodeList[i].id);
    obj.addEventListener('mouseover', function () {
        obj.innerHTML = '*';
    }, false);
}

Upvotes: 1

Views: 50

Answers (1)

timaschew
timaschew

Reputation: 16602

You should use the event argument in the event handler, otherwise obj is the last assignent (assigned in the loop).

And you don't need any Utility helper

var nodeList = document.getElementsByTagName('p');

for(var i = 0; i < nodeList.length; i++)
{ 
    var obj = nodeList[i];
    obj.addEventListener('mouseover', function(e){
        e.target.innerHTML = '*';
    }, false);
}

http://jsfiddle.net/002efeht/

Upvotes: 1

Related Questions