The primary issue with your code is that the class name candidate
does not exist anywhere in your HTML. If your goal is to reference the "ADD" button with this class, then you either need to change its class to candidate
in your HTML, or change your JS to reference its actual class, item
.
Furthermore, getElementsByClassName
returns, as its name suggests, a NodeList
of multiple elements, rather than a single element. This means that you'll need to select a single element from that list upon which to act; your code, in contrast, treats this method as though it returned only a single element to be acted upon directly (i.e., a Node
instead of a NodeList
). For your addItem
function, this change is trivial; there's only one element with the item
class, so simply select the first element of the NodeList
(i.e., element 0
). For the removeItem
function, assuming you want to remove the most recently-added nodes first (LIFO-style), you'll need to remove the last element in the NodeList
(if one exists) from the DOM. See the updated snippet below for all of these changes and some explanatory comments:
function addItem(){
var ul = document.getElementById("dynamic-list");
// We know that the "candidate" is always the first—and only—element with the class name "item"
var candidate = document.getElementsByClassName("item")[0];
var li = document.createElement("li");
li.setAttribute('class',candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
}
function removeItem(){
var ul = document.getElementById("dynamic-list");
// We know that the "candidate" is always the first—and only—element with the class name "item"
var candidate = document.getElementsByClassName("item")[0];
// The "items" variable is introduced to hold the list of all added ".hello" elements, the last of which we will remove
var items = document.getElementsByClassName(candidate.value);
// Safety check: it's possible that there are no more ".hello" elements remaining, in which case there's nothing to remove
if (items.length > 0) {
// Access the last element of the NodeList and remove it from the DOM
var item = items[items.length - 1];
ul.removeChild(item);
}
}
<ul id="dynamic-list"></ul>
<button type="submit" class="item" value="hello" onclick="addItem()">ADD</button>
<button onclick="removeItem()">remove item</button>