0

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.

0

3 Answers 3

7

using jQuery:

$('#testElem').remove();
$('body').append($('<div id="testElem"></div>'));
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

display is more often useful than visibility because setting display to none will remove the element from the flow, rather than just not rendering it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.