views:

34

answers:

2

Hello there, It's seems very curious but I'm having problems applying styles for javascript generated elements in IE7 but if I render the same element as string it does work.

on my javascript:

var style = document.createElement('link');
    style.setAttribute('type','text/css');
    style.setAttribute('rel', 'stylesheet');
    style.setAttribute('href', url('assets/default.css'));

document.getElementsByTagName('head')[0].appendChild(style);

this will create the script tag which I like to embed into the page, which contains:

.sample{
  background: red;
}

and then for the page I'm adding a .sample span to the body:

var sample = document.createElement('span');
    sample.setAttribute('class','sample');
    sample.innerHTML = 'hello there';

document.getElementsByTagName('body')[0].appendChild(sample);

When rendering on IE8/FF/Safari/Chrome, etc it renders quite well with the red background, surprisingly on IE7 it doesn't display the red background. It works if I convert the sample element to a string and then add it to the body, but then I lost all the references being made to that element, which is no good.

so the question is: How can I apply styles correctly to the javascript elements?

thanks in advance

+3  A: 

Could you try changing this:

sample.setAttribute('class','sample');

to this:

sample.className = 'sample';

As Andy E mentioned in the comments, in IE 7 and lower setAttribute() blindly maps the attribute you supply to a property name (e.g. it maps sample.setAttribute('class', 'sample') to sample.class = 'sample'), so it breaks for attributes like class, for, onload, onclick, etc. where the HTML attribute name is different to the JavaScript property name.

Paul D. Waite
Although `setAttribute` seemed to work for you when adding the stylesheet, so that’s probably not it...
Paul D. Waite
Paul, surprisingly it worked! it seems there's an issue with the `class` keyword as an attribute indeed. Thanks a lot
ludicco
+1. *setAttribute()* incorrectly maps to property names in IE7 and lower, so it breaks for a quite attributes like *class*, *for*, *onload*, *onclick*, etc.
Andy E
Aha! Well done chaps, I’ll amend my answer accordingly.
Paul D. Waite
+1  A: 

You should manipulate the element directly when applying classes, e.g.:

var sample = document.createElement('span');
sample.className = 'sample';
sample.innerHTML = 'hello there';

sample.style.backgroundColor = '#ff25e1';

Interestingly, you can't use the word, "class", because it is a reserved word in JS.

Andrew
But `'class'` as a string isn't a reserved keyword, so that shouldn't really matter.
peirix
You are right. You can use `setAttribute()` any way you want. Likewise, you can also write `sample['class'] = 'sample';`, though it would have the same result as `setAttribute()`. But for direct assignment, you can't write `sample.class = 'sample';`. That's all I meant.
Andrew