Cross-browser dynamic CSS property setting
I have a function that gets a lot of data and sets a CSS property for a specific element.
Here is the code:
function setStyle(element,property,target){
element.style[property] = target;
}
var EL = document.getElementById("id");
setStyle(EL,"width","50px");
It works well in most browsers, but not IE6-IE9.
I found document.defaultView.getComputedStyle
and element.currentStyle[type]
, but these methods are getting styled and I cannot use them to install.
Is there a way to do this for older IEs?
I don't want to use jQuery or any other JS library , thanks.
source to share
The default will be element.style.property = "value"
, for example:
document.getElementById("id").style.width = "50px";
There is no reason why it shouldn't work. But alternatively, consider setting the css style on a class and adding it to an element using a property className
. It is widely supported:
CSS
.myClass { width: 50px; }
JS:
document.getElementById("id").className = "myClass";
EDIT
Another way that works in IE8 + (unless you really need anything below) would set the actual attribute style
on the DOM element, so you can get the property as a parameter:
function setStyle(element,property,target){
element.setAttribute("style", property + ":" + target);
}
var el = document.getElementById("test");
setStyle(el, "color", "red");
source to share