Reputation: 495
I want to remove all elements when clicking a button that have the same class "box". I have looked up several examples where people do this, but I'm still having trouble figuring out how to do it for my code.
I have this function which adds a box to the DOM when a button is clicked.
function addBox(newbox) {
var scene = document.getElementById("scene"); //where all new divs will go
var div = document.createElement("div");
div.className += " " + "box"; // assigns the class "box" to all divs
div.innerHTML += newbox.name;
div.style.backgroundColor = newbox.color;
scene.appendChild(div);
}
This is the function I'm working on to try to clear all of the new divs when a different button is clicked.
function clear() {
var elems = document.getElementsByClassName("box");
for ( k = elems.length - 1; k >= 0; k--) {
parentElement.removeChild(elems[k]);
}
}
The warning that I'm getting in the console is "parentElement is not defined". I have been trying to figure out how to define the parent element but I'm having trouble. any help is appreciated. thanks
Upvotes: 1
Views: 3623
Reputation: 71908
You can grab the parent from the element's parentNode
property:
function clear() {
var elems = document.getElementsByClassName("box");
for (var k = elems.length - 1; k >= 0; k--) {
var parent = elems[k].parentNode;
parent.removeChild(elems[k]);
}
}
Upvotes: 4