David G
David G

Reputation: 96810

Error while trying to set style with JavaScript

var d = document;
div = d.body.appendChild(d.createElement("DIV"));
div.id = "hi";
div.innerHTML = "Hello World";

cssStyle = ["fontFamily", "fontStyle"];
cssAn = ["Arial", "italic"];

div.style.cssStyle[0] = cssAn[0];

It does not set the style. Instead it returns an error stating "Cannot set property 0 of undefined". What could I have done wrong?

Upvotes: 1

Views: 279

Answers (3)

Erik Kaplun
Erik Kaplun

Reputation: 38227

This is not Javascript related — it's a general programming principle.

You have a variable cssStyle that contains "fontFamily" and "fontStyle".

Accessing the property cssStyle of div.style is in no way related to the variable cssStyle.

You need to div.style[cssStyle[0]] = cssAn[0].

EDIT:

Additionally, if you want all properties whose names are in cssStyles and corresponding values in cssAn to be set on div, then, assuming cssStyle and cssAn have the same number of elements, you can:

for (var i = 0; i < cssStyle.length; i += 1) {
    var name = cssStyle[i];
    var value = cssAn[i];
    div.style[name] = value;
}

Upvotes: 1

Liza Daly
Liza Daly

Reputation: 2963

cssStyle is not a property of div.style. You want:

div.style[cssStyle[0]] = cssAn[0];

Upvotes: 6

Elian Ebbing
Elian Ebbing

Reputation: 19037

I think you want:

div.style[cssStyle[0]] = cssAn[0];

Upvotes: 6

Related Questions