...

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



chrissecord
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");
t.setAttribute("class","myclass");

gusblake
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.

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

RandomUser531
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.

gusblake
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