[英]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,其中包含代表产品的元素,这些元素具有cart-item类。
<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?
我怎样才能做到这一点?
jQuery: $('#insert-zone').empty();
jQuery的:
$('#insert-zone').empty();
Or if you don't want to clean it up completely: $('.cart-item').remove();
或者,如果您不想完全清除它:
$('.cart-item').remove();
Also you need a button. 您还需要一个按钮。 So:
所以:
$('#button-id').on('click', function() {
$('.cart-item').remove();
});
This will remove all the div elements that have class cart-item
under ol #insert-zone
: 这将删除所有在
ol #insert-zone
下具有类cart-item
的div元素:
var ol = document.getElementById('insert-zone');
var div = ol.getElementsByClassName('cart-item');
for(var i=0;i<div.length;i++)
ol.removeChild(div[i]);
This is very simple to do with jQuery 使用jQuery很简单
Here is an example I just whipped up: http://jsfiddle.net/anUqB/ 这是我刚刚举过的一个例子: http : //jsfiddle.net/anUqB/
HTML: 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 Java脚本
$("#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
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.