Timo Vossen
Timo Vossen

Reputation: 313

How to remove all elements with the same class

So I have a system were the user of the site can create div's and all these div's get different class names, with all these div's there will also be created a delete button with the same class. How do you remove the button and the div with the same class on click on the button.

I figure'd it would be something like this:

$("div.Test").remove();

only than with a this tag.

Upvotes: 9

Views: 24406

Answers (4)

renke
renke

Reputation: 1230

First you need to get the class of the button you clicked, then find the div with the same class and remove it. Later, just remove the button you clicked on:

$("#your-button-id").click(function() {
    var className = $(this).attr('class'); // find the button class
    $('div.' + className).remove(); // remove the div with the same class as the button
    $(this).remove(); // remove the button
});

Upvotes: 0

jtrohde
jtrohde

Reputation: 442

Within the click event of your button:

var thisClass = $(this).attr("class");
$('div.' + thisClass).remove();

Upvotes: 13

Gregg Duncan
Gregg Duncan

Reputation: 2725

You need a way of selecting all the buttons. I would create the buttons with a class that you can use for access and use a data attribute to hold the class of the divs to remove. like this:

<button class="remove-btn" data-remove="div-class">Remove</button>

Then you can do something like this:

$(function(){
    $('.remove-btn').on("click", (function(){
        var remove = $(this).data('remove');
        $('.' + remove).remove();
        $(this).remove();
    });
});

Upvotes: 0

void
void

Reputation: 36703

$("button").click(function(){

   $("div."+$(this).attr('class')).remove();
   // $("."+$(this).attr('class')).remove(); to remove both button and div

});

Assuming button has just a single class name that too match with the class name of the div.

Upvotes: 1

Related Questions