JS: How to remove items from a list when they are checked and button clicked?
14,476
getElementById
only returns one element, it doesn't select the descendants of an element that has a specific id, you can use the .querySelectorAll()
method:
var x = [].slice.call(document.querySelectorAll("#items-listed li"));
x.filter(function(e) {
// Filtering the `li` that has a checked input child
return e.firstChild.checked;
}).forEach(function(e) {
e.remove(); // e.parentNode.removeChild(e);
});
Note that above code won't work in older browsers, for supporting those browsers you can use a for loop:
var x = document.getElementById("items-listed"),
c = x.childNodes;
for (var i = 0; i < c.length; i++) {
if (c[i].nodeType === 1) {
if (c[i].firstChild.checked) {
x.removeChild(c[i--]);
}
}
}
Comments
-
Beast_Code almost 2 years
I am trying to remove items in a list when they are checked-off and then the remove button clicked. I think my problem may be in the removeItem function.
var x = document.getElementById("items-listed <li>");
because when i remove<li>
the entire list is removed.<div> <div id="center-container"> <h4>Enter an Item for Your Shopping List:</h4> <hr /> <form name="form"> <label for="item">Item:</label> <input type="text" placeholder="Shopping Items" id="item" name="itemEntered" /> <input type="button" value="Enter" id="Enter" onclick="javascript:addItem();" /> </form> </div> </div> <div> <div id="items-container"> <h4>Your list of Items:</h4> <form> <input type="button" value="Remove selected items" onclick="javascript:removeItem();" /> </form> <hr /> <ul id="items-listed"> </ul> </div> </div> function addItem() { var item = []; item = document.getElementById('items-listed'); item.innerHTML += "<li><input type='checkbox'>" + document.form.itemEntered.value + "</li>"; } function removeItem () { var x = document.getElementById("items-listed <li>"); x.remove(); }
-
Manuel Richarz about 10 yearsbut check the browser-compatibility of querySelectorAll: developer.mozilla.org/en-US/docs/Web/API/…
-
Admin about 10 yearsYou can't miss this warning : "This is an experimental technology" :) developer.mozilla.org/en-US/docs/Web/API/ChildNode.remove.
-
Beast_Code about 10 years@BlackSheep are there simpler ways?
-
Ram about 10 years@JonaTheApprentice Well, DOM API doesn't have fancy methods for doing this, specially the older versions. You can use jQuery if you don't like the syntax.
-
Ram about 10 years@wared Yes, it is an experimental method. I have added the alternative
.removeChild()
. -
Admin about 10 yearsThis is great :) I wasn't aware of that.