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.

+3


source to share


2 answers


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:

http://jsfiddle.net/ppf5qcvo/

function setStyle(element,property,target){
    element.setAttribute("style", property + ":" + target);
}
var el = document.getElementById("test");
setStyle(el, "color", "red");

      

+2


source


Are you considering using jQuery? It handles all cross-browser issues for you. You can do the same with the following statement:



$('#id').width('50px');

      

0


source







All Articles