Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an element that can remove it self?

I'm building a lightbox as a school project, and I can't use jQuery. I've got an image. When you click it, Javascript makes a transparent div with the ID "overlay". I want the div to remove itself, or the parent to remove it but it doesn't work. I think it has to do with the fact that you can't link 'onclick' to an element that doesn't exists yet.

like image 342
Sam Avatar asked Mar 27 '13 00:03

Sam


Video Answer


3 Answers

You have to remove the element from the parent. Something like this:

d = document.getElementById('overlay');
d.parentNode.removeChild(d);

Or you could just hide it:

d.style.display = 'none';

And, oh: you can add Javascript code to a (newly created) element by assigning a function to the onclick attribute.

d = document.createElement('div');
d.onclick = function(e) { this.parentNode.removeChild(this) };
like image 65
bart Avatar answered Sep 30 '22 12:09

bart


You can remove the element like the following

var el = document.getElementById('div-02');
el.remove(); // Removes the div with the 'div-02' id

Click here for more details

like image 37
Masum Billah Avatar answered Sep 30 '22 13:09

Masum Billah


Don't use the onclick handler in the tag, use Javascripts event functions such as addEventListener to dynamically add the event to the elements. You should also make sure that when you remove the elements you properly clean up all your references (in other words, unregister the event handlers).

like image 21
Brandon Buck Avatar answered Sep 30 '22 13:09

Brandon Buck