Introduction
Using JavaScript to make HTML element, often is used elem.setAttribute("style", "property1:val; property2:val;")
to set CSS properties in easy way; but there's a problem if you had just set a CSS property with elem.style.prop="val"
: it will be reset to default browser value!! (Run the test code showed below.)
So I made a simple function to solve this problem and continue to use a setAttribute
-like approach.
Using the Code
I wrote the setStyle
method in HTMLElement
interface, that represents any HTML element, so to use it easily.
This is the function:
HTMLElement.prototype.setStyle = function(str) {
var props = str.split(";");
for(var i = 0; i < props.length; i++) {
var t = props[i].split(":");
this.style[fixPropName(t[0].trim())] = t[1].trim();
}
}
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
function fixPropName(str) {
var tArray = str.split("-");
var prop = tArray[0];
for(var i = 1; i < tArray.length; i++) {
prop += tArray[i].capitalize();
}
return prop
}
Now you can use this function, in this way:
var div = document.getElementById("IdElement");
div.setStyle("background:blue; color: white");
This function is just a millisecond (on my PC, and sometimes) slower than setAttribute
method, but now you are sure to haven't unexpected CSS properties change.
To make a test, run this code:
<script>
HTMLElement.prototype.setStyle = function(str) {
var props = str.split(";");
for(var i = 0; i < props.length; i++) {
var t = props[i].split(":");
this.style[fixPropName(t[0].trim())] = t[1].trim();
}
}
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
function fixPropName(str) {
var tArray = str.split("-");
var prop = tArray[0];
for(var i = 1; i < tArray.length; i++) {
prop += tArray[i].capitalize();
}
return prop
}
window.addEventListener("DOMContentLoaded",
function(e) {
var div = document.getElementById("cc");
div.style.opacity = "1";
str = "Opacity: " + div.style.opacity + "<br />";
var endTime, startTime = Date.now();
div.setAttribute("style","background:green;color:black");
endTime = Date.now();
str += "TimeExec: " +(startTime-endTime) + "<br />";
str += "Opacity: " + div.style.opacity + "<br /><br />";
div.style.opacity = "1";
str += "Opacity: " + div.style.opacity + "<br />";
startTime = Date.now();
div.setStyle("background:blue; color: white");
endTime = Date.now();
str += "TimeExec: " +(endTime-startTime) + "<br />";
str += "Opacity: " + div.style.opacity + "<br />";
div.innerHTML = str;
}, false);
</script>
<div id="cc">To to to</div>
Updates
31/01/2014:
Added
fixPropName function to transform property text from, for example, background-color to backgroundColor