Brian
Brian

Reputation: 877

How can I remove an element added by jquery?

I want list items moved to a div when clicked and vice versa. But it seems, only elements loaded from the source can be moved.

How can I do that? Thanks.

 <div class="green">
    <ul id="selectable">
        <li class="content-item">Item A</li>
    </ul>
</div>


<div class="red">
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
    <span class="selected-item">Item 1</span>
</div>

<script>

$(".selected-item").click(function() {
    var text =  "<li class='content-item' >"+$(this).text()+"</li>";
    $(".green #selectable").prepend( text );
    $(this).remove();
});

$(".content-item").click(function() {
    var text =  "<span class='selected-item'>"+$(this).text()+"</span>";
    $(".red").append( text );
    $(this).remove();
});
</script>

http://jsfiddle.net/wGz8s/112/

Upvotes: 1

Views: 61

Answers (2)

Buzinas
Buzinas

Reputation: 11725

You should use jQuery's event delegation.

The problem is: your jsFiddle is using jQuery 1.4 (very old version), and it doesn't have the .on event.

I've updated it to the version 1.11, and it works like a charm:

$(".abc").on("click", "span", function(e) {
    var text =  "<li class='content-item' >"+$(e.target).text()+"</li>";
    $(".choices #selectable").prepend( text );
    $(e.target).remove();
});

$(".choices").on("click", "li", function(e) {
    var text =  "<span class='selected-item'>"+$(e.target).text()+"</span>";
    $(".abc").append( text );
    $(e.target).remove();
});

http://jsfiddle.net/wGz8s/113/

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to use event delegation here since the elements that you are adding at the runtime would not be available during event binding,

$(document).on("click",".selected-item", function() {
   var text =  "<li class='content-item' >"+$(this).text()+"</li>";
   $(".green #selectable").prepend( text );
   $(this).remove();
});

and

$(document).on("click",".content-item", function() {
  var text =  "<span class='selected-item'>"+$(this).text()+"</span>";
  $(".red").append( text );
  $(this).remove();
});

And in the place of the document in my code use a static closest dom element of the selector which is being passed inside .on()

Upvotes: 1

Related Questions