jQuery Append and Remove

12,484

Solution 1

Since your question was kind of vague and lacked markup I used a basic checkbox example for the demo. I've included a link to a live demo at jsFiddle here

HTML:

<input type="checkbox" id="test" /> Check me

<div id="items"></div>

JavaScript:

$("#test").bind('click', function(){

  var $t = $(this);

  if($t.is(':checked')){
    // append item
    $('#items').append('<span class="selected">I was recently appended.</span>');
  }else{
    // empty div and remove it from DOM (empty helps with memory leak issues with remove() )
    $('span', '#items').empty().remove();
  }
});

Solution 2

I believe a more better approach might be to store the result of each append to an array or a variable and loop through that when you remove the elements. For a single element,

// Appending
var ele = $('<span>', {
    html: 'nbsp;', 
    class: 'selected'
}).appendTo(container);

// Removing
ele.remove();

If you're doing this from within an event handler, the variable ele should be defined in the outside scope, so that it is accessible afterwards. For multiple items:

// Appending
var ele = [];
ele.push($('<span>', {
    html: 'nbsp;', 
    class: 'selected'
}).appendTo(container));

// Removing
for(var i = 0; i < ele.length; i++){
    ele[i].remove();
}

Again, the array ele should be defined outside of the scope of any event handlers. Otherwise, the other answers to this question will work too.

Share:
12,484
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to use this jQuery to append some HTML and then unappend it

    if( !(jQuery(check).hasClass('selected'))){
        jQuery(this).append('<span class="selected">&nbsp;</span>');
       }    
    

    How am I able to do this and also live update it ? I am just trying to add this element when a user "clicks" on or "off" ?

    i.e. if check does not have the class "Selected" - append - else remove ?