Javascript 动态添加/删除 div 到 html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4967289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dynamically adding/removing a div to html
提问by jslearner
I want to dynamically create a div
element with id="xyz"
. Now before creating this, I want to remove any other div
with id ="xyz"
if it exists. How can i do it?
我想div
用id="xyz"
.动态创建一个元素。现在在创建之前,我想删除任何其他的div
,id ="xyz"
如果它存在的话。我该怎么做?
var msgContainer = document.createElement('div');
msgContainer.setAttribute('id', 'xyz'); //set id
msgContainer.setAttribute('class', 'content done'); // i want to add a class to it. it this correct?
var msg2 = document.createTextNode(msg);
msgContainer.appendChild(msg2);
document.body.appendChild(msgContainer);
}
How can i remove all divs with id =xyz
if they exist before executing above code?
id =xyz
在执行上述代码之前,如何删除所有 div(如果它们存在)?
回答by T.J. Crowder
Removing:
删除:
var div = document.getElementById('xyz');
if (div) {
div.parentNode.removeChild(div);
}
Or if you don't control the document and think it may be malformed:
或者,如果您不控制文档并认为它可能格式不正确:
var div = document.getElementById('xyz');
while (div) {
div.parentNode.removeChild(div);
div = document.getElementById('xyz');
}
(Alternatives below.)
(下面的替代方案。)
But you only need the loop with invalid HTML documents; if you control the document, there's no need, simply ensure the document is valid. id
values mustbe unique. And yet, one sees plenty of documents where they aren't.
但是您只需要带有无效 HTML 文档的循环;如果您控制文档,则不需要,只需确保文档有效即可。id
值必须是唯一的。然而,人们会看到大量文件不在它们的位置。
Adding:
添加:
var msgContainer = document.createElement('div');
msgContainer.id = 'xyz'; // No setAttribute required
msgContainer.className = 'someClass' // No setAttribute required, note it's "className" to avoid conflict with JavaScript reserved word
msgContainer.appendChild(document.createTextNode(msg));
document.body.appendChild(msgContainer);
If you don't like the code duplication in my loop above and you think you need the loop, you could do:
如果您不喜欢我上面循环中的代码重复,并且您认为需要循环,则可以执行以下操作:
var div;
while (!!(div = document.getElementById('xyz'))) {
div.parentNode.removeChild(div);
}
or
或者
var div;
while (div = document.getElementById('xyz')) {
div.parentNode.removeChild(div);
}
...although that last may well generate lint warnings from various tools, since it lookslike you have =
where you mean ==
or ===
(but in this case, we really do mean =
).
...虽然这最后可能产生的各种工具lint警告,因为它看起来像你有=
,你的意思是==
或者===
(但在这种情况下,我们确实平均值=
)。