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

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

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
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"];

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



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

// switching the element from the list 2 to the list 1{

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
handler disappeared the second time ? Is the
method removing children object's handlers?

Answer Source

As per jquery doc

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