Adam Haile
Adam Haile

Reputation: 31339

Element.appendChild() chokes in IE

I have the following javascript:

  css = document.createElement('style');
  css.setAttribute('type', 'text/css');
  css_data = document.createTextNode('');
  css.appendChild(css_data);
  document.getElementsByTagName("head")[0].appendChild(css);

for some reason, in IE only, it chokes on "css.appendChild(css_data);" Giving the error: "Unexpected call to method or property access"

What's going on?

Upvotes: 4

Views: 12226

Answers (4)

Adam Haile
Adam Haile

Reputation: 31339

@crescentfresh

I tried your suggestion, and the content of the style block simply never gets populated. Tried in IE6 and IE7... it just doesn't seem to do anything

Here's my modified code:

function load_content()
{
  var d = new Date();

  css = document.createElement('style');
  css.setAttribute('type', 'text/css');
  if(css.styleSheet) { css.styleSheet.cssText = 'testing'} //Because IE is evil
  else { css_data = document.createTextNode(''); css.appendChild(css_data); } //And everyone else is cool
  document.getElementsByTagName("head")[0].appendChild(css);

  new Ajax.PeriodicalUpdater('content', '/%doc_path%?'+d.getTime(),
  {
    method: 'post',
    frequency: 5,
    onSuccess: function(transport) {
          new Ajax.Request('/%css_path%?'+d.getTime(), {
              method: 'get',
              onSuccess: function(transport) {

                if(css.styleSheet) { css.styleSheet.cssText = transport.responseTex}
                else { 
                    var new_css_data = document.createTextNode(transport.responseText);
                    css.replaceChild(new_css_data, css_data); 
                    css_data = new_css_data;
                } 
              }
          });
    }
  });
}

Any ideas?

Upvotes: 0

ForYourOwnGood
ForYourOwnGood

Reputation: 40392

no appendChild() allowed with HTMLStyleElement in I.E.

check it out

Upvotes: 0

Luca Matteis
Luca Matteis

Reputation: 29267

This is particular with the "style" element, IE doesn't allow the appendChild() method on it.

Upvotes: 0

Crescent Fresh
Crescent Fresh

Reputation: 116980

Try instead:

var css = document.createElement('style');
css.setAttribute('type', 'text/css');

var cssText = '';
if(css.styleSheet) { // IE does it this way
    css.styleSheet.cssText = cssText
} else { // everyone else does it this way
    css.appendChild(document.createTextNode(cssText));
}

document.getElementsByTagName("head")[0].appendChild(css);

Upvotes: 14

Related Questions