Optimization Monday — Part VII: set CSS in one step
Optimization Monday January 7th, 2008Often you need to set just a single CSS attribute in your web application. You will usually do this by applying a value to the specified style attribute.
myElement.style.color = 'red';
Sometimes you will have to set a number of attribute values at once. For example if you have just created an element and can not assign a CSS class, because all attributes depend on specified conditions. In this case it is significant faster to set a value for the whole style attribute instead of setting each CSS attribute.
This five assignments
var myDiv = document.createElement('div'); myDiv.style.backgroundColor = 'blue'; myDiv.style.border = 'solid 4px red'; myDiv.style.fontFamily = 'Helvetica, Arial'; myDiv.style.width = '400px'; myDiv.style.height = '100px';
can be combined into one
var myDiv = document.createElement('div'); myDiv.setAttribute('style', 'background-color:blue;border:solid 4px red;font-family:Helvetica, Arial;width:400px;height:100px;');
If you are dealing with dynamically created elements, be sure to read part three of this series. ;-)
January 7th, 2008 at 08:35
It is good to mention that this is not a good idea for non-dynamically created elements e.g. queried existing elements, because using this construct means to overwrite all other existing styles.
July 30th, 2009 at 02:11
yea fine statements above :D …;)