Vladimir Potapov
Vladimir Potapov

Reputation: 2437

How do I remove all elements with a particular class name from the DOM?

I have a div with elements representing products, which have the cart-item class.

<div id="cart">
    <h1 class="ui-widget-header">Demostration Site</h1>

    <div class="ui-widget-content">
        <ol id="insert-zone" class="ui-droppable ui-sortable">
            <li class="placeholder" style="display: none;">Add your items here</li>
            <div class="item-container cart-item"></div>
            <div class="item-container cart-item"></div>
            <div class="item-container cart-item"></div>
            <div class="item-container cart-item"></div>
            <div class="item-container cart-item"></div>
            <div class="item-container cart-item"></div>
            <div class="item-container cart-item"></div>
        </ol>
    </div>
</div>

I want to have a button that, upon being pressed, clears all items with class cart-item to get an empty cart. How can I do this?

Upvotes: 0

Views: 268

Answers (3)

Prasath K
Prasath K

Reputation: 5018

This will remove all the div elements that have class cart-item under ol #insert-zone:

var ol = document.getElementById('insert-zone');
var div = ol.getElementsByClassName('cart-item');

for(var i=0;i<div.length;i++)
   ol.removeChild(div[i]);

Upvotes: 3

frenchie4111
frenchie4111

Reputation: 399

This is very simple to do with jQuery

Here is an example I just whipped up: http://jsfiddle.net/anUqB/

HTML:

<div id="cart">
    <div class="item-container cart-item">item</div>
    <div class="item-container cart-item">item</div>
    <div class="item-container cart-item">item</div>
    <div class="item-container cart-item">item</div>
    <div class="item-container cart-item">item</div>
    <div class="item-container cart-item">item</div>
</div>
<button id="clear">Clear</button>

Java Script

$("#clear").click( function() { //When the button with id "clear" is pressed
    $(".cart-item").each( function() { // Find an iterate through each item with class "cart-item"
       $(this).remove(); // Remove the item
    });
});

Upvotes: 2

Kristoffer K
Kristoffer K

Reputation: 2053

jQuery: $('#insert-zone').empty();

Or if you don't want to clean it up completely: $('.cart-item').remove();

Also you need a button. So:

$('#button-id').on('click', function() {
   $('.cart-item').remove();
});

Upvotes: 4

Related Questions