1
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?

2
  • Sorry. I'm new to this site. I don't even know how to do that... Commented Apr 2, 2011 at 14:16
  • The FAQ would be a good start. Commented Apr 2, 2011 at 14:18

3 Answers 3

6

I think you want:

div.style[cssStyle[0]] = cssAn[0];
Sign up to request clarification or add additional context in comments.

Comments

6

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

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

Comments

1

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

1 Comment

As a side note, you should rename cssStyle to styleAttrs and cssAn to styleValues to signify that both are arrays. Also, if you want to be correct, CSS means the actual .css files or inline style sheets in the HTML file. Styles that you assign in your JS code (or directly using a style="..." HTML attribute) are, well, just styles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.