Search code examples
javascripthtmlinternet-exploreronloadappendchild

InvalidCharacterError with appendChild on onload in IE only


I'm trying to execute a Javascript function in IE11, but i get an InvalidCharacterError on appendChild.

function fixWidth(){
   var elems=document.getElementsByTagName("*");
   for(e=0; e<elems.length; e++){
      var eCurStyle = elems[e].currentStyle;
      var l_minWidth = (eCurStyle.minWidth) ? eCurStyle.minWidth : eCurStyle.getAttribute("min-width"); 
      if(l_minWidth && l_minWidth != 'auto'){
         var shim = document.createElement("DIV");
         shim.style.cssText = 'margin:0 !important; padding:0 !important; border:0 !important; line-height:0 !important; height:0 !important; BACKGROUND:RED;';
         shim.style.width = l_minWidth;
         shim.appendChild(document.createElement("&nbsp;"));
         elems[e].appendChild(shim);
      }
   }
}
window.onload = fixWidth;

It works correctly on IE8. But not on IE11.


Solution

  • This is a bug in IE8, not in IE11, as doing

    document.createElement("&nbsp;")
    

    shouldn't really work anywhere, as a non-breaking space is not an element.
    Chrome gives the error

    Uncaught InvalidCharacterError: Failed to execute 'createElement' on 'element': The tag name provided ('&nbsp;') is not a valid name.

    and I'd suspect almost any browser but IE8 would throw an error on that

    If you want to add a non-breaking space to the element, you could do

    shim.innerHTML = shim.innerHTML + "&nbsp;";