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

using jQuery:

$('#testElem').remove(); $('body').append($('<div></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 > <div > <div > ..... 

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

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy