2012-09-05 157 views
0

我试图删除我动态创建的元素。这是我如何创建它...动态删除元素

var divTag = document.createElement("div"); 
divTag.id = "affiliation"; 
divTag.innerHTML = "Stuff Here"; 

我试过几种方法去除它没有成功。这是迄今为止我所拥有的。

var A = document.getElementById('affiliation'); 
A.parentNode.removeChild(A); 

建议?

+0

你希望使用jQuery? –

+0

我宁愿做纯JavaScript。不过,我很乐意听到任何建议。 – user1612226

+0

@ user1612226 - 你确定这不起作用吗?我一直都这样做。 –

回答

0

如果您希望使用jQuery的,这是很容易消除:

$("#affiliation").remove(); 

对于普通的JavaScript,您可以使用此:

var node = document.getElementById("affiliation"); 
if (node.parentNode) { 
    node.parentNode.removeChild(node); 
} 
+1

也许'$(“#affiliation”)。remove();' –

0

你追加到身体还是父母?

var divTag = document.createElement("div"); 
divTag.id = "affiliation"; 
divTag.innerHTML = "Stuff Here"; 
document.body.appendChild(divTag); 


element = document.getElementById("affiliation"); 
element.parentNode.removeChild(element);​ 
0

这段代码对我来说很好。唯一的区别是我加的是“联系” divTag的身体

function insert() { 
    var divTag = document.createElement("div"); 
    divTag.id = "affiliation"; 
    divTag.innerHTML = "Stuff Here"; 
    document.body.appendChild(divTag); 
} 
function remove() { 
    var A = document.getElementById('affiliation'); 
    A.parentNode.removeChild(A); 
}