删除子节点错误

时间:2013-04-20 20:45:03

标签: javascript

我遇到下面的代码问题,我在Opera中一直收到这个错误:

Uncaught exception: DOMException: NOT_FOUND_ERR

这在Chrome中:

Uncaught Error: NOT_FOUND_ERR: DOM Exception 8

此消息引用removeInput函数:

function addInput() {
  var div = document.createElement("div");
  var txt = "<div>Upload image: <input type='file' name='slika[]' /> <span onclick='removeInput(this.parentNode)' />Remove <img src='catalog/remove_icon.png' /></span></div>";
  div.innerHTML = txt;
  document.getElementById('text').appendChild(div);
}

function removeInput(el) {
  document.getElementById('text').removeChild(el);
}

问题是:如何删除addInput函数预先创建的元素?这是删除动态元素的正确方法吗?

2 个答案:

答案 0 :(得分:1)

el.parentNode.removeChild(el);

答案 1 :(得分:0)

首先:您不需要在innerHTML中编写“<div>”,因为默认情况下createElement会创建“<div></div>”。

for second:如果要删除最后插入的元素,则需要在插入全局变量

后保存它
var lastInserted = null;
function addInput() {
  var div = document.createElement("div");
  var txt = "Upload image: <input type='file' name='slika[]' /> <span onclick='removeInput(this.parentNode)' />Remove <img src='catalog/remove_icon.png' /></span>";
  div.innerHTML = txt;
  document.getElementById('text').appendChild(div);
  lastInserted = div;
}

function removeInput() {
  if(!lastInserted)return;
  document.getElementById('text').removeChild(lastInserted);
}
相关问题