SetStyle: Set CSS Properties Without Surprises





0/5 (0 vote)
With the method proposed here, you can set CSS in an easy way, as with setAttribute-style, but without surprises
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(";"); //get properties
for(var i = 0; i < props.length; i++) {
var t = props[i].split(":"); //t[0] = property - t[1] = value
this.style[fixPropName(t[0].trim())] = t[1].trim(); //trim removes white space(s)
}
}
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
//transform text, for example, from background-color to backgroundColor
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(";"); //get properties
for(var i = 0; i < props.length; i++) {
var t = props[i].split(":"); //t[0] = property - t[1] = value
this.style[fixPropName(t[0].trim())] = t[1].trim(); //trim removes white space(s)
}
}
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 + "
";
var endTime, startTime = Date.now();
div.setAttribute("style","background:green;color:black");
endTime = Date.now();
str += "TimeExec: " +(startTime-endTime) + "
";
str += "Opacity: " + div.style.opacity + "
";
div.style.opacity = "1";
str += "Opacity: " + div.style.opacity + "
";
startTime = Date.now();
div.setStyle("background:blue; color: white");
endTime = Date.now();
str += "TimeExec: " +(endTime-startTime) + "
";
str += "Opacity: " + div.style.opacity + "
";
div.innerHTML = str;
}, false);
</script>
To to to