简体   繁体   中英

How to add and remove Div tag dynamically with javascript

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'

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?

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.

using jQuery:

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

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

The solution is like the following :

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

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

-----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

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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