javascript 如何使用javascript动态添加和删除Div标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7305014/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:41:06  来源:igfitidea点击:

How to add and remove Div tag dynamically with javascript

javascriptjqueryhtml

提问by brybam

How would i simply remove and and add a div in realtime? and yest I already have the div made manually on the page so it will be there to be removed even the first time the function is ran. The div is called 'testElem'

我将如何简单地实时删除和添加一个 div?是的,我已经在页面上手动创建了 div,因此即使第一次运行该功能时,它也会被删除。该 div 称为“testElem”

I'm trying:

我正在努力:

            var remDiv = document.getElementById('testElem');
            document.body.removeChild(remDiv);

             var divTag = document.createElement("div");
            divTag.id = "testElem";
            document.body.appendChild(divTag);

but the script isn't working. I tried placing an "alert" to test after the first remDiv. But its not even making it past there. The code breaks. In chrome i tried going to tools>Javascript console, but there are no errors. Is there a better way to debug javascript so I can see what the error is?

但脚本不起作用。我尝试在第一个 remDiv 之后放置一个“警报”进行测试。但它甚至没有让它过去。代码断了。在 chrome 中,我尝试转到工具> Javascript 控制台,但没有错误。有没有更好的方法来调试 javascript 以便我可以看到错误是什么?

I'm just trying to do this so it will delete the content thats in the div every time the function is ran so the content doesn't double up. It's different every time.

我只是想这样做,所以它会在每次运行该函数时删除 div 中的内容,这样内容就不会加倍。每次都不一样。

回答by Samich

using jQuery:

使用jQuery:

$('#testElem').remove();
$('body').append($('<div id="testElem"></div>'));

回答by xsari3x

An alternative solution is to make a list of all div's you need and then alternate the style property called visibility

另一种解决方案是列出您需要的所有 div,然后替换称为可见性的样式属性

The solution is like the following :

解决方法如下:

-----HTML------

-----HTML------

<div id="div1" style="visibility:hidden;"  >
<div id="div2" style="visibility:hidden;"  >
<div id="div3" style="visibility:hidden;"  >
.....

-----JS--------

-----JS--------

//to Hide
var x=document.getElementById("divToHide");
x.style.visibility="visible"; 
//to show 
ar x=document.getElementById("divToShow");
x.style.visibility="hidden";


This solution also give you a better control where the div will be placed

此解决方案还可以让您更好地控制 div 的放置位置

回答by yoavmatchulsky

removeChildneed to be called from the parent of the div you want to remove.

removeChild需要从要删除的 div 的父级调用。

so you'd want this code:

所以你想要这个代码:

var remDiv = document.getElementById('testElem');
var parent = remDiv.parentNode;
parent.removeChild(remDiv);

var divTag = document.createElement("div");
divTag.id = "testElem";
parent.appendChild(divTag);