Friday, September 17, 2010

Dynamic add style to element

Previously I have problem setting the styles of elements from Javascript. I end up changing the className of the element to achieve the desired effect. Recently, I saw from some one's blog saying that using the following method can actually change element style dynamically.

document.getElementById("myid").style.cssText="font-size:20px;font-weight:bold;"

This method works for both IE (tested in IE6,IE7) and Firefox (ver 3.6).

Note that you actually replaces the old style with your new style using this method.

To add style to existing styles do this

document.getElementById("myid").style.cssText +="color:red"

I noticed that IE7 does not add new style element to the existing style if you don't prepend a ";"

Note that it still replaces the old style if the added element already exists.

No comments:

Post a Comment