Lurk21
Lurk21

Reputation: 2337

javascript getElementById is null - Id passed by this

Maybe I'm not using 'this' right.

HTML:

<div style="margin: 4px; padding: 10px; border: solid 1px;" onmouseover="darken(this);">

JavaScript:

function darken(elt) {
    "use strict";
    document.getElementById(elt.id).style.backgroundColor = "#e8e8e8";
}

?

Upvotes: 0

Views: 83

Answers (4)

Travis J
Travis J

Reputation: 82267

jsFiddle Demo

The first issue is that there is no id on that element so you cannot use document.getElementById to find it.

An advantage that you can use is that you already passed the element with this:

function darken(elt) {
 "use strict";
 elt.style.backgroundColor = "#e8e8e8";
}

Upvotes: 3

Sachin
Sachin

Reputation: 40970

You havn't provided any Id to your div element

<div id="myDiv" style="margin: 4px; padding: 10px; border: solid 1px;" onmouseover="darken(this);">

JS Fiddle Demo

Upvotes: 1

zzzzBov
zzzzBov

Reputation: 179046

this is a reference to the element. You could simply use it as:

function darken(elt) {
    elt.style.backgroundColor = '#e8e8e8';
}

Upvotes: 3

Rick Viscomi
Rick Viscomi

Reputation: 8852

If you have a reference to the element, there's no need to lookup its ID then query the document for the element matching that ID. (There is no ID assigned to that element by the way).

Upvotes: 4

Related Questions