Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot remove a div in Javascript

Tags:

javascript

I'm trying to remove a div in Javascript but 'its not working. I get no error in my console yet the function does get called.

I don't understand what I have done wrong, so I'm hoping someone can explain. This is how it works:

function menu_load(type){
  document.getElementById(type).onclick = function(){ menu_unload(type); }
  var width = 100;
  var height = 100;
  var d = document.createElement('div');
  d.id = 'menu';
  d.className = 'menu';
  d.style.width = width + 'px';
  d.style.height = height + 'px';
  document.getElementById('G').appendChild(d);
}

function menu_unload(type){
  alert('test'); //this displays
  var div = document.getElementById("menu");
  div.parentNode.removeChild(div); // doesn't remove the div
  document.getElementById(type).onclick = menu_load(type);
}

window.onload = function(){
  menu_load('test');
}

Is there any mistake here that I have missed? I just can't work out the problem.

like image 930
Sir Avatar asked Dec 18 '25 14:12

Sir


1 Answers

Your code works for me if I correct the following line:

document.getElementById(type).onclick = menu_load(type);

Which incorrectly calls menu_load() and tries to assign the result to .onclick. It should be like you did in the other function

document.getElementById(type).onclick = function() { menu_load(type); };

Demo: http://jsfiddle.net/MCZza/

To be honest I don't know why this fixes it, since your code wasn't actually a syntax error, but because it called menu_load() it recreated the div just removed. and the .removeChild() line should happen first, but anyway...

like image 84
nnnnnn Avatar answered Dec 20 '25 06:12

nnnnnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!