Hi all,
I'm trying to remove a div using JavaScript. I've noticed that the best way to do this is to use the parentNode of the element we want to manipulate.
Here's the basic code:
Code:
var cont1 = document.getElementById('MSG_cont1');
cont1.parentNode.removeChild(cont1);
The #MSG_cont1 div **IS** removed successfully, and that element ID does exist before removal (I checked it before and after, using the DOM inspector). Nonetheless, I get a "cont1 is null" message on the Error Console, after running this code. Why is that? By the way, the parentNode is the <BODY> element.
Cheers!
It shows '[object HTMLDivElement]'... Now I'm lost.
Here's how the div is being created:
Code:
var parentElem = document.getElementById('doc_body');
var new_div = document.createElement('div');
new_div.setAttribute('id','MSG_cont1');
parentElem.appendChild(new_div);
Are you "pretty sure" or do you "absolutely know"? When this line is called during the process of rendering the page can also make a difference.
I absolutely know. I managed to host the page and the entire js code at http://filmen.planetaclix.pt/test.
Both DIVs to be removed ('MSG_cont1' and 'MSG_cont2') are also generated through JS using the 'toggleMsg' function.
Thanks for your inputs.
I absolutely know. I managed to host the page and the entire js code at http://filmen.planetaclix.pt/test.
Both DIVs to be removed ('MSG_cont1' and 'MSG_cont2') are also generated through JS using the 'toggleMsg' function.
Thanks for your inputs.
You have nested divs with the same onclick handler applied to them, which means there will be multiple attempts to remove the same element.
Yep, that was it. I applied the handler to different divs assuming that only one of them in the stack would actually be 'clickable'. Now it works perfectly. Cheers!
Bookmarks