Search code examples
javascriptcompatibilitybackwards-compatibility

Internet Explorer 'InsertHTML' compatibility issue


I am currently having issues with Internet explorer and a Javascript that I created. I've been trying to find where the incompatibility issue originates from, but I've been unable to pinpoint it.

This works fine in Firefox 26, but it doesn't seem to actually generate a table in Internet Explorer 11.

function InsertTable()
{
column = document.getElementById("Columns").value
row = document.getElementById("Rows").value

cellwidth = 100 / column

table = '<table width="100%" border="2px">'

while(row > 0)
{
columncopy = column
table = table + '<tr>'

while(columncopy > 0)
{
table = table + '<td width="' + cellwidth + '%"></td>'
columncopy = columncopy - 1;
}

table = table + '</tr>'
row = row - 1;
}

table = table + '</table>'

document.getElementById("mainedit").focus();
document.execCommand('insertHTML', false, table);


}

Update: I managed to narrow down the issue to a single line of code, it is going through the entire thing and not actually placing it correctly.

document.execCommand('insertHTML', false, table);

Is the source of the issue.


Solution

  • I found the following code and integrated it in the following manner.

    html = table
    
    IE()
    
    
    function IE()
    {
    
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
    
            // Range.createContextualFragment() would be useful here but is
            // only relatively recently standardized and is not supported in
            // some browsers (IE9, for one)
            var el = document.createElement("mainedit");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
    
            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
    
    
    }