Apply CSS styles to element using the JavaScript
Every DOM element has the style property which allow us to manipulate the CSS of the element.
The style property gives a read-write access to the element style.
With the style property it is possible to change the most CSS properties using it.
For e.g: element.style.width = “250px”; will change the attribute of the element style = “width:250px”;
CSS has the multi word property seprated by the -(hypen). While using this CSS multi word property in the JavaScript we have to camelCase it:
For e.g:
background-color => backgroundColor
margin-top => marginTop
padding-top => paddingTop
z-index => zIndex
Apply CSS properties
The value assigned to the style property will always override the CSS properties. So whatever we assigned to the style property will be adopted by the CSS properties.
Now let’s set the CSS attribute using the style property.
var element = document.getElementById("divStyles"); element.style.width = "300px"; element.style.height = "300px"; element.style.backgroundColor = "#ADACAC"; element.style.color = "#FFFFFF"; element.style.border = "3px red dashed";
Reset to default CSS properties
We also can revert the changes by just applying the empty string(”).
var element = document.getElementById("divStyles"); element.style.width = ""; element.style.height = ""; element.style.backgroundColor = ""; element.style.color = ""; element.style.border = "";
Read CSS properties
The style property give access only to properties set through it.
It means style property only read those CSS attribute which is set through the style property.
var divStyles = document.getElementById("divStyles"); var backgroundColor = divStyles.style.backgroundColor; // It will be return the empty string because the // backgroundColor property is not set with the style property alert(backgroundColor);
In above example style.backgroundColor will be return the empty string because CSS attribute background-color is not set through the style property.
var divStyles = document.getElementById("divStyles"); divStyles.style.width = "200px"; var width = divStyles.style.width; // It will return the 200px because the // It is set by the style propoerty alert(width);
Now above example style.width will return the 200px, because this value is set by the style property.
cssText
cssText is only property which allow us to add the !important.
Any style.property can not accept and not do any action on the !important statment.
So the cssText is only way to add the !important and made the CSS attribute changes effectivley.
var divStyles = document.getElementById("divStyles"); divStyles.style.cssText = "background-color: #ADACAC !important; \ width: 100%; \ padding: 10px; \ color: #FFFFFF;";
In the block of the cssText, we have to use the CSS attribute.