Jump to content

Change class with javascript


music_lp90

Recommended Posts

<style type="text/css">  .old {	color: red;  }  .new {	color: blue;  }</style><script type="text/javascript">  function changeClass() {	var d=document.getElementById("change");	d.className="new";  }</script><input type="button" onclick="changeClass()" value="Click Me"><div id="change" class="old">This should change to blue.</div>

Link to comment
Share on other sites

It's better to use setAttribute, and to use both class and className. Only IE uses className I think.

  function changeClass() {	var d=document.getElementById("change");	d.setAttribute("className", "new");	d.setAttribute("class", "new");  }

Link to comment
Share on other sites

It's better to use setAttribute, and to use both class and className. Only IE uses className I think.
  function changeClass() {	var d=document.getElementById("change");	d.setAttribute("className", "new");	d.setAttribute("class", "new");  }

Why is that better?The variant
d.className="new";

is shorter and is a cross browser way. True, it's not a DOM standard, but if you ask me, when it comes to JavaScript, using a standard API is the least imporant thing. As long as you keep the markup and script separate, produce a standards compliant (and similarly - accessible) markup and degrade gracefully with JS off, it doesn't matter which API you use to reach the end result, as long as it works for the above mentioned cases. Keeping it as efficient and as small as possible should, I think, be the thing to judge as to which way you go with in simpler cases like this one, and the ".className" approach is it.

Link to comment
Share on other sites

True, it's not a DOM standard, but if you ask me, when it comes to JavaScript, using a standard API is the least imporant thing.
Oh geez, you've never had to develop Javascript for IE4/Netscape4 have you? Believe me, when everyone uses one standard API it's a good thing. As far as setAttribute not being cross-browser, which browsers don't support it?
Link to comment
Share on other sites

Oh geez, you've never had to develop Javascript for IE4/Netscape4 have you? Believe me, when everyone uses one standard API it's a good thing. As far as setAttribute not being cross-browser, which browsers don't support it?
I meant "standard" in terms of "W3C DOM standard". I too believe having a standard is a good thing. I just don't think in the case of JavaScript is as important as making the thing work with less code. And as for setAttribute() - well, IE has problems with it. The above mentioned with class being one of the better examples.(and no, I haven't done any JavaScript for those browsers... I admit I am guilty of that)
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...