简体   繁体   中英

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?

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);

这特别是“style”元素,IE不允许使用appendChild()方法。

no appendChild() allowed with in IE 不允许使用appendChild()

check it out

@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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM