Element.appendChild() chokes in IE

前端 未结 4 1693
予麋鹿
予麋鹿 2020-12-03 19:36

I have the following javascript:

  css = document.createElement(\'style\');
  css.setAttribute(\'type\', \'text/css\');
  css_data = document.createTextNode(         


        
相关标签:
4条回答
  • 2020-12-03 20:17

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

    0 讨论(0)
  • 2020-12-03 20:17

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

    0 讨论(0)
  • 2020-12-03 20:18

    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);
    
    0 讨论(0)
  • 2020-12-03 20:26

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

    check it out

    0 讨论(0)
提交回复
热议问题