Thibaut Guirimand Thibaut Guirimand -4 years ago 38
Javascript Question

Children handlers disappeared after removing and readding element

I try to switch elements between two HTML lists. In the first list, a new element must be at the end of the list. I use the jQuery

.appendTo()
method to add an element and
.remove()
to remove an element. In the second list every elements must stay in place so I use
.hide()
and
.show()
.

Here is my HTML lists :

List 1
<ul id="l1"></ul>
List 2
<ul id="l2"></ul>


An element of one of my lists looks like :
<li>Element - <span>remove</span></li>


I add an handler to the
span
to remove the element from the list and add it in the other list.

let ul1 = $("ul#l1"),
ul2 = $("ul#l2"),
lis = ["ga", "bu", "zo", "meu"];


lis.forEach(function(e){
let li1 = $("<li>" + e + "- </li>"),
sp1 = $("<span>remove</span>"),
li2 = $("<li>" + e + "- </li>"),
sp2 = $("<span>hide</span>");

sp1.appendTo(li1);
li1.appendTo(ul1);

sp2.appendTo(li2);
li2.appendTo(ul2);
li2.hide();

// switching the element from the list 1 to the list 2
sp1.on("click", function(){
li2.show();
li1.remove();
});

// switching the element from the list 2 to the list 1
sp2.click(function(){
li2.hide();
li1.appendTo(ul1);
});
});


The problem is that after re-adding the element to the first list, the handler seems to have disappeared. I add this element the same way as the first time.

Why has the
.click()
handler disappeared the second time ? Is the
.remove()
method removing children object's handlers?

Answer Source

As per jquery doc

https://api.jquery.com/remove/

all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download