I already implemented a function, that creates divs inside another div and want to give user an option to remove all of these divs with one single button but I cant get it to work, I'm probably doing something prohobited with DOM so I will be grateful for any advice. Here is my code:
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber" onchange="return addMoreDice()">
<button onclick="addDice()">Add Dice</button>
<div id="diceTable">
</div>
<button onclick="removeDice()">Reset</button>
and JS:
var numInput = document.querySelector("input");
function addDice(){
var div = document.createElement('div');
div.className = "diceStyle";
div.innerHTML = Math.floor((Math.random()*6)+1);
document.getElementById('diceTable').appendChild(div);
};
function addMoreDice(){
for(var i = 0; i < numInput.value; i++){
addDice();
}
}
function removeDice(){
var removeDiv = document.getElementsByClassName("diceStyle");
removeDiv.remove();
}
I thought it would be a "clever" way to just remove with a single button all elements with that class name but I guess that isnt the best idea.
edit
I do realize the problem was solved before, but Im encountering problems with the solution proposed in the thread, it doesnt work in my case, it only does half of its job and I dont understand why.
function removeDice(){
var removeDiv = document.getElementsByClassName("diceStyle");
for(var i=0; i < numInput.value; i++){
removeDiv[i].remove();
}
} Removes only half of my divs. It works exactly the same if I iterate with removeDiv.lentgh