0

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

Community
  • 1
  • 1
Matti Mazur
  • 83
  • 2
  • 8

1 Answers1

3

Problem is here

var removeDiv = document.getElementsByClassName("diceStyle");
removeDiv.remove();

removeDiv is array now. Try to remove each element using

for(var i = 0 ; i < removeDiv.length; i++) {removeDiv[i].remove();}
Johan Willfred
  • 811
  • 7
  • 14
  • Im encountering similiar problem when I initially tried to remove it using a loop ( i did `for(var i = 0 ; i < numInput.value; i++) {removeDiv[i].remove();}` The problem is the function is only removing half of the divs. So if i have 10 divs, then it removes 5, then 3, then 1 and 1. – Matti Mazur Mar 16 '17 at 10:25
  • ok, use this ) ` function removeDice() { document.getElementById('diceTable').innerHTML = '' }` Just replace all inner html to empty string) – Johan Willfred Mar 16 '17 at 10:49
  • 1
    when `i` becomes a half of array initial length, array has half length as well. I mean current length of array = initial length / 2. thus when `i = current length + 1`, the index points to nowhere. – Banzay Mar 16 '17 at 11:10
  • Thanks Johan, simple but actually good idea. Banzay that makes sense – Matti Mazur Mar 16 '17 at 15:43
  • `for(var i=0; i < numInput.value; i++){ removeDiv[numInput.value-i-1].remove(); }` I tried this and this also works now, thank you guys, Ill have both options now – Matti Mazur Mar 16 '17 at 15:46