简体   繁体   English

动态删除元素

[英]Removing element dynamically

I'm trying to remove an element that I created dynamically. 我正在尝试删除我动态创建的元素。 This is how I created it... 这就是我创造的方式...

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

I've tried several methods of removing it without success. 我尝试了几种方法将其删除均未成功。 Here's what I have so far. 到目前为止,这就是我所拥有的。

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

Suggestions? 有什么建议吗?

If you wish to use jQuery , it is very easy to remove: 如果您想使用jQuery ,则很容易删除:

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

For the normal JavaScript , you can use this: 对于普通的JavaScript ,您可以使用以下代码:

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

Did you appended to the body or a parent? 您是附属于身体还是父母?

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


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

This snippet just works for me fine. 这个片段对我来说很好。 The only difference is I added the "affiliation" divTag to the body 唯一的区别是我在正文中添加了“隶属关系” 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);
}

Check Node.removeChild 检查Node.removeChild

var A = document.getElementById("affiliation");
if (A.parentNode) {
    A.parentNode.removeChild(A);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM