Reputation: 203
I have a function that gets many pieces of data and sets a CSS property for a defined 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 for IE6–IE9.
I've found document.defaultView.getComputedStyle
and element.currentStyle[type]
, but these methods get style and I can't use them to set.
Is there any way to do that for old IEs?
i don't want to use jQuery or any other JS library, thanks.
Upvotes: 3
Views: 1458
Reputation: 16821
The default way would be element.style.property = "value"
, like:
document.getElementById("id").style.width = "50px";
There's no reason why it shouldn't work. But, as an alternative, consider setting the css style in a class, and adding it to the element by the className
property.. It is widely supported:
css:
.myClass { width: 50px; }
js:
document.getElementById("id").className = "myClass";
EDIT
Yet another way around, that works in IE8+ (If you don't really need anything lower) would be setting the actual style
atribute to 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");
Upvotes: 2
Reputation: 238
Have you considered using jQuery? It handles all the cross browser issues for you. You could accomplish the same thing with the following statement:
$('#id').width('50px');
Upvotes: 0