Lion King
Lion King

Reputation: 33823

`this` object does not return an object

I have two codes, one to work on modern browsers like(IE9+, ff, Ch, etc), and another to work with old browsers like (ie6,7).

For modern browsers.

var elements = document.getElementsByTagName('p');
for (i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', function () {
        this.style.backgroundColor = 'yellow';
    });
}

For old browsers (ex: ie6,7)

var elements = document.getElementsByTagName('p');
for (i = 0; i < elements.length; i++) {
    elements[i].attachEvent('onclick', function () {
        this.style.backgroundColor = 'yellow'; // here is the problem in `this` object.
    });
}

The first code work fine, because this return an object correctly.

But the second code does not work fine, because this does not return an object correctly.
The error message that appear in IE 6,7: Unable to set value of the property 'backgroundColor': object is null or undefined

What is the problem ?, and how can I solve it ?

Upvotes: 0

Views: 70

Answers (2)

Lion King
Lion King

Reputation: 33823

The solution of the problem on IE 6,7 .

var elements = document.getElementsByTagName('p');
for (i = 0; i < elements.length; i++) {
    elements[i].attachEvent('onclick', function () {
        window.event.srcElement.style.backgroundColor = 'yellow';
    });
}

Also another way.

var elements = document.getElementsByTagName('p');
var event = window.event;
for (i = 0; i < elements.length; i++) {
    elements[i].attachEvent('onclick', function (event) {
        event.srcElement.style.backgroundColor = 'yellow';
    });
}

Upvotes: 0

anurupr
anurupr

Reputation: 2344

this does not point to the current target element in IE versions < 9

Refer this.style.backgroundColor don't work in IE7/8

Upvotes: 1

Related Questions