View Full Version : What's the correct way to set an attribute on a DOM object?

07-19-2010, 07:51 PM
Which of these is the correct way to set the className attribute, or are they both okay?

option 1:

var t = document.createElement("p");
t.className = "myclass";

option 2:

var t = document.createElement("p");

07-19-2010, 08:24 PM
Both are OK, but .className is more cross browser compatible. I'm not sure how far back support in Internet Explorer goes, but to be on the safe side I would generally stick to dot/square bracket syntax.

07-19-2010, 08:29 PM
good to know. Thanks.

07-19-2010, 09:02 PM
Never use setAttibute unless direct assignment fails, and the only time I have encountered that is when setting properties of an <embed> element.

07-19-2010, 11:41 PM
Document objects returned by AJAX calls also use get-/setAttribute.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum