IE: Invalid target element - appending table using innerHTML + string

丶灬走出姿态 提交于 2019-12-22 06:41:21

问题


In Internet Explorer this line document.getElementById("left").getElementsByTagName("tbody")[0].innerHTML = document.getElementById("left").getElementsByTagName("tbody")[0].innerHTML + string; is giving me a SCRIPT600: Invalid target element for this operation. …character 10

The string is simply that which contains a set of tablerows. This works fine in Chrome, Safari or Firefox. Is there a better way of doing this? What I am doing is once the user gets to the bottom of the page I am appending tablerows into the table to load more content. It's a sort of AJAX infinite scrolling type of deal - client requested. I am using Javascript and would prefer to stay with Javascript at this point and not change to jQuery just for this task.

Update also the same with: document.getElementById("left").innerHTML = document.getElementById("left").innerHTML + string; Also, left is <table id="left">


回答1:


Yes you will need to wrap them first like this:

var div = document.createElement("div");
div.innerHTML = "<table><tbody>" + string + "</tbody></table>";

document.getElementById("left")
  .appendChild(div.firstChild.tBodies[0]);



回答2:


Slightly different way for when you need to insert a table row at the end of the table. Your new code, e.g. a new <tr>, should be in the variable called html.

if (document.attachEvent) { //if using old IE
    var currentTable = document.querySelector("#myTable");
    var currentTableHTML = currentTable.outerHTML;

    //replace closing tag with new code + closing tag
    currentTableHTML = currentTableHTML.replace("</tbody>", html + "</tbody>";

    currentTable.parentNode.removeChild(currentTable);

    //reinsert the table before some other element - you can use something else if you have a container for the table
    document.querySelector("#someElement").insertAdjacentHTML("beforebegin", currentTableHTML);
}
else {
    //use insertAdjacentHTML in a normal browser
}


来源:https://stackoverflow.com/questions/15148406/ie-invalid-target-element-appending-table-using-innerhtml-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!