.InnerHTML Not working properly in Internet Explorer

后端 未结 10 1574
一个人的身影
一个人的身影 2020-12-19 08:55

I wanted to assign a link tag to innerHTML of a HTML control. But this is not working properly in Internet Explorer. However when I try to assign anything other than &

10条回答
  •  执笔经年
    2020-12-19 09:25

    innerHTML won't work in IE, but using DOM methods it will:

    function getValue()
    {
      var x=document.getElementById("myHeader")
        , link = document.createElement('link')
        , div = document.createElement('div');
      x.innerHTML = '';
      x.appendChild(link);
      x.appendChild(div);
      div.innerHTML = 'abc';
      link.href = 'http://test.com/css/template.css';
      link.rel = 'stylesheet';
      alert(x.innerHTML);
    }
    

    Although the reference states a link tag may only appear in the header, interesting enough the style link does work if you use the code I provided, in all browsers I tried (IE, firefox, chrome). See this jsfiddle (where I used a real css-href from test.com ;-)

    If you however want to place the link in it's rightful section (), use:

    var header = document.getElementsByTagName('head')[0];
      , link = document.createElement('link');
    header.appendChild(link);
    link.href = 'http://test.com/css/template.css';
    link.rel = 'stylesheet';
    

提交回复
热议问题