Tauseef Hussain
Tauseef Hussain

Reputation: 1079

Jquery remove element

I am basically trying to print the value of a button in the div with list class if the button is selected. Also remove the same value wwhen it is deselected. I am able to print the value successfully but not able to remove it. Could somebody please help me out with it.

var buttonSelect = $(".btn").click(function() {
    if ($(this).hasClass('active')){
        $(".list").append(this.value + "   ")
    }
    else {
        $(".list").remove(this.value)
    }
});

Upvotes: 3

Views: 7718

Answers (3)

thomas
thomas

Reputation: 905

If you want to remove the element itself along with everything in it, just use jQuery’s remove() method.

$(document).ready(function() {
    $("button").click(function() {
        $("div").remove();  //remove Div element
    });
});

You can see an example here: How to Remove Elements from DOM in jQuery

Upvotes: 1

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

The parameters from .remove() is a selector, just having a value in there that contains the content of the element you want to remove will not work. For example if I had this:

<li class="list">test</li>

Doing $(".list").remove("test") will not remove it. You will probably want to use the :contains selector (since you may have the value with spaces at the end). So in the example above doing $(".list").remove(":contains('test')") will remove the element. You can do the same thing in your case:

$(".list").remove(":contains('"+this.value+"')");

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

You should rather append the content along with html element like span:

$(".btn").click(function() {
if ($(this).hasClass('active')){
     $(".list").append('<span class="newval_'+this.value+'">'+this.value + "</span>");
}else{ 
     $(".list").find('.newval_'+this.value).remove();
}});

Upvotes: 2

Related Questions