Search code examples
javascriptcssdynamicstylesheetelement

IE7 - Styling Javascript generated Element


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


Solution

  • 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.