Do not use the style property on HTML objects
Since ajax, a lot of people have to create HTML on the fly depending on response of the request. One mistake that I see a lot is that people are using the style property of their HTML objects. Why shouldn’t I do it?
The style property has a precedence on every style
Because the style property is so “close” to the HTML object, it will override every other style from a CSS file. So if you begin to write styles in your javascript code, you’ll have to do it all the time. It might be easy and clean for a basic project but it will become a mess in the future. You should centralize every style in your CSS files so you won’t have to search where you assigned a style.
Example
I have this CSS
[source:css]
div.theCssClass {
background-color:blue;
}
[/source]
and I create a new HTML object of this class
[source:javascript]
// I create the DIV
var div = document.createElement(“div”);
div.appendChild(document.createTextNode(“This div is a test”));
div.className = “theCssClass”; // I assign theCssClass
div.style.backgroundColor = “red”; // The background is red
document.body.appendChild(div);
[/source]
You’ll see that the even if I set the background color to blue in the CSS file, the background will be red because I used the style property.
The !important in CSS
If you want to override a style assigned in javascript, you could always use the !important statement in your CSS file.
[source:css]
div.useThisOne {
background-color:blue !important;
}
[/source]
Use it only if you really have to. I wouldn’t recommend !important because it breaks the default behavior of styles and can become very messy. When all is important, nothing is important.