I knew had I heard it before but I must have completely missed it anyway and forgotten to test my new Javascript widget in IE. None of the stylesheet worked in IE and it didn't make any sense. Here's how I did it first:

var closer = document.createElement('a');
a.setAttribute('style', 'float:left; font-weight:bold');
a.onclick = function() { ...

That worked in Firefox of course but not in IE. The reason is that apparently IE doesn't support this. This brilliant page says that IE is "incomplete" on setAttribute(). Microsoft sucked again! Let's now focus on the workaround I put in place.

First I created a function to would take "font-weight:bold;..." as input and convert that to "element.style.fontWeight='bold'" etc:

function rzCC(s){
  // thanks http://www.ruzee.com/blog/2006/07/\
  // retrieving-css-styles-via-javascript/
  for(var exp=/-([a-z])/; 
      exp.test(s); 
      s=s.replace(exp,RegExp.$1.toUpperCase()));
  return s;
}

function _setStyle(element, declaration) {
  if (declaration.charAt(declaration.length-1)==';')
    declaration = declaration.slice(0, -1);
  var k, v;
  var splitted = declaration.split(';');
  for (var i=0, len=splitted.length; i<len; i++) {
     k = rzCC(splitted[i].split(':')[0]);
     v = splitted[i].split(':')[1];
     eval("element.style."+k+"='"+v+"'");

  }
}

I hate having to use eval() but I couldn't think of another way of doing it. Anybody?

Anyhow, now using it is done like this:

var closer = document.createElement('a');
//a.setAttribute('style', 'float:left; font-weight:bold');
_setStyle(a, 'float:left; font-weight:bold');
a.onclick = function() { ...

and it works in IE!

ivo van der Wijk - 08 January 2007 [«« Reply to this]
node.style.cssText = "..." usually does the trick for me
Peter Bengtsson - 09 January 2007 [«« Reply to this]
Really? I'll give that a try.
tjallen - 21 November 2007 [«« Reply to this]
Hooray! Thank-you.

In my case, involving styles of a div element, this worked only after I append the div to the body node, but yes!
state-machine - 29 January 2008 [«« Reply to this]
Yes, this is a really short solution! Thank you all for not giving up on this topic. By the way - it's not possible to code a lot of JavaScript for HTML using the DOM only, is it?
Frank - 31 July 2009 [«« Reply to this]
Nice !!! Thx
sanjeev - 02 December 2010 [«« Reply to this]
thnx...it worked!!!
Brittany - 09 February 2007 [«« Reply to this]
thanks, it works well!
Ra - 21 May 2007 [«« Reply to this]
BEFORE

var closer = document.createElement('a');
//a.setAttribute('style', 'float:left; font-weight:bold');

_setStyle(a, 'float:left; font-weight:bold');
a.onclick = function() { ... }

----------------------
AFTER

var closer = document.createElement('a');
//closer.setAttribute('style', 'float:left; font-weight:bold');

_setStyle(closer, 'float:left; font-weight:bold');
closer.onclick = function() { ... }

If type 'closer' it's work

Thanks Peter :D
Matt - 08 January 2008 [«« Reply to this]
Just what I was looking for.

Thanks a lot!
agent47 - 03 May 2008 [«« Reply to this]
Wow that was great buddy ! You saved me a lot of weeks. I need to personally thanks you too.
LP - 15 June 2008 [«« Reply to this]
Hi, it helped me to fix appending of new style values, without overwritting all previously declared ones (just those that are meant to change). Thanks.
If you still don't like eval(), try this:
element.style[k]= v;
You know objects, arrays, objects...
adrian lee - 11 July 2008 [«« Reply to this]
Thanks a lot! perfect code!!!
Luis Serrano - 29 July 2008 [«« Reply to this]
This is great! I've improved it just a bit:

_setStyle: function (aElement /* object */, aDeclaration /* CSS Declaration */) {
try {
if (aElement) {
aDeclaration = aDeclaration.replace(/\s+/g,''); // remove all white spaces
if (document.all) { // IE Hack
if (aDeclaration.charAt(aDeclaration.length-1)==';')
aDeclaration = aDeclaration.slice(0, -1);
var k, v;
var splitted = aDeclaration.split(';');
for (var i=0, len=splitted.length; i<len; i++) {
k = rzCC(splitted[i].split(':')[0]);
v = splitted[i].split(':')[1];
eval("aElement.style."+k+"='"+v+"'");
}
return (true);
} else { // The clean way
aElement.setAttribute ('style', aDeclaration);
return (true);
}
}
} catch (e) {
return (false);
}
}

Hope you like it. Good job mate ;)
Luis Serrano - 29 July 2008 [«« Reply to this]
I forgot to tell why I decided to "improve" it: if you put a white space in the css declaratio, such:

background-color: #FFFFFF;

the original code will miss it. You had to put it together for it to work, like:

background-color:#FFFFFF;

Oh, and the function declaration in my version is for prototype. If you don't use this technique just change the declaration to:

function _setStyle (aElement /* object */, aDeclaration /* CSS Declaration */)

That's it.

Cheers!
Jason - 03 September 2008 [«« Reply to this]
I found myself having issues with this same problem today and have found out a few interesting things.

In IE (they just have to be different don't they) the style attribute is actually treated as an Element. You can set the different style properties by using the syntax shown below.

oNewDiv = createElement('div');
oNewDiv.style.setAttribute('border', '1px solid #000');
oNewDiv.style.setAttribute('backgroundColor', '#fff');

Of course, this fails terribly in firefox :(

However, I have always been able to set styles without the setAttribute function in a cross browser supported way like:

oNewDiv.style.backgroundColor = '#fff';
Pascal - 05 September 2008 [«« Reply to this]
This won't work at all for me, using IE 7 or 8..
Raj Shah - 20 October 2008 [«« Reply to this]
eval() is devil. this workaround is not going to help. infact it will hang your IE and fill your memory with bunch of variables.

If you code little smart using conditions if(document.all) { code here }else{ code here } then everything will be cool.

I've tried and it's working in all browsers.
Anonymous - 06 January 2009 [«« Reply to this]
Try using cssText for ie.
Element.style.setAttribute('cssText', 'left:150px;.........
you could create function if you wanted.
Emanuele Caldarola - 17 February 2009 [«« Reply to this]
thanks very very very much!
Emanuele Caldarola - 17 February 2009 [«« Reply to this]
I have added this code:

if(k=='class')
{
eval("element.className='"+v+"'");
}
Vimal - 02 March 2009 [«« Reply to this]
@ivo van der Wijk=You're a genius man!!!
I know it sounds very exagerrated but what the hell... u just saved me a couple of hours of searching
Quiquelie - 15 June 2009 [«« Reply to this]
Hi,

Try this:

var closer = document.createElement('a');
a.style.float="left";
a.style.fontWeight="bold";
a.onclick = function() { ...

It works on all browsers !! Enjoy it !!
ramesh - 04 November 2009 [«« Reply to this]
Hi Quiquelie,
Your code is cool thanks :) i was literally searching for onclick cross browser functionality
Marko Sacher - 07 July 2009 [«« Reply to this]
Hi,
how is this?
element.style[k]= v;
instead of eval(...)
Messias - 17 August 2009 [«« Reply to this]
Cool!!
thxs!
Chris - 16 May 2010 [«« Reply to this]
Works like a charm! I definitely needed this dynamic!! Thanks so much!
Anonymous - 29 June 2010 [«« Reply to this]
I like how you automatically escaped the newline in the commented code ;-P
Anonymous - 08 September 2010 [«« Reply to this]
set one or more objects to one or more styles
{obj1,obj2...},{"color":"red","fontSize":"small","fontFamily":"Cursive"...}
works in FF,IE,Safari

function a_obj_setstyle(a_obj,a_prop){
for (ko in a_obj){for(kp in a_prop){
eval('a_obj[ko].style.'+kp+'="'+a_prop[kp]+'"');
}}
}
Mohsen Elgendy - 27 November 2010 [«« Reply to this]
OMG, your a very smart, you just saved my ass, my client was going to kill me ,, lol

Thanks a lot body ;)
Marcellino Bommezijn - 23 December 2010 [«« Reply to this]
This is how it works in IE

oImg.style.cssText="float:left;margin-right:7px;margin-bottom:7px";
Steve Bucknall - 06 November 2011 [«« Reply to this]
The simple solutions are always the best.
Thanks
Anonymous - 06 December 2012 [«« Reply to this]
NICE!
Anonymous - 23 December 2010 [«« Reply to this]
THAAAAANXXXXXX!!!!
You're the best web programmer!!!!!

I hate IE...

Thanks a lot!!!!
ivo - 08 August 2011 [«« Reply to this]
Hello guys,

If you have short form in your style like :

font: normal normal bold xx-small verdana, serif;

This cut function will cut the spaces and mix the css -->
font:normalnormalboldxx-smallverdana,serif;
mathanraj - 14 December 2011 [«« Reply to this]
Oh thats work great... thankssssssss.....
Jonathan - 04 January 2012 [«« Reply to this]
I had a similar issue with setAttribute not working on IE. I put it in a try block, and in the catch block I used outerHTML for the IE version. outerHTML is read/write, so my function could dynamically get the code of the existing control, and then replace whatever had to change. One quirk is that IE rewrites the control's code in outerHTML, so I had to work around that a little, but it worked.
Alex Huang - 12 March 2012 [«« Reply to this]
thanks ur code, but if i want to remove one of css that i added, how can i do that????
Anonymous - 24 April 2012 [«« Reply to this]
document.getElementById('name').className = "yourClass";
Aidiakapi - 24 June 2012 [«« Reply to this]
People, DO NOT USE eval(). Especially not in such an easy cases.

eval("element.style."+k+"='"+v+"'");
is almost identical (I'll explain) to this:
element.style[k] = v;

When you create an object: var obj = { a: 1, b: 2, c: 3 };
You can (get or) set the values like:
obj.a = 10
which is identical to:
obj["a"] = 10

As to where that eval("element.style."+k+"='"+v+"'"); differs from the direct method is that if you'd try to set for example a background image, this'd be the css:
background-image: url('/images/someImage.png')
If you use that in the eval, this is the code that'll be evaluated:
element.style.backgroundImage='url('/images/someImage.png')'
Which obviously results in a syntax error because of the single quotes. Of course that could be solved by first replacing \ into \\ and then ' into \'.

Eval is evil, there are rarely ever situations where there's need for eval, and even if there are try your absolute best to find a way around.
Such a small change avoids:
1. The performance hit you have from using eval()
2. Making your code less secure (for example, if some 3rd party code executes: _setStyle(someElement, "width: 10px' alert('My evil message, muauauauaua') var rndDump = '; height: 10px;"), it would of course run the injected code)
3. Spreading bad code like this across other people's sites, possibly harming the identity and privacy of people browsing the web.
Peter Bengtsson - 24 June 2012 [«« Reply to this]
It's been many years since I wrote that but I think the point is that the stupid eval was necessary because of IE.
Then again, I've stopped caring about it working in IE.
Aidiakapi - 30 June 2012 [«« Reply to this]
Unless you're doing commercial work that's always a good choice :P.
Nevertheless even in IE this eval wasn't necessary :).

And I also know that this is an old article, but these are still the articles beginners find when they run into this issue, and that's why I made the comment.
Event at my old company where I had co-workers who all finished collage for web development, and they still didn't know how to write proper javascript and had all sorts of hacky scripts like this one in their code.


Your email will never ever be published