function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
function add(identifier, html){
var frag = create(html);
document.body.insertBefore(frag, document.getElementById(identifier));
}
identifier
是我在开发人员工具中验证过的标签的字符串 id,html
只是我想添加到表示的元素前面的片段标识符
。 frag
是一个可靠的 html 片段,对 getElementById
的调用返回一个可靠的元素,即两者都不是字符串。为什么我在 insertBefore
上收到上述错误?
最佳答案
您的元素可能不是 document.body
的直接子元素。试试这个 ->
function add(identifier, html){
var frag = create(html),
el = document.getElementById(identifier);
el.parentNode.insertBefore(frag, el);
}
关于javascript - Uncaught Error : NOT_FOUND_ERR: DOM Exception 8 on insertBefore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15914288/