I created this JavaScript code which detects the value (number) of select
tags and creates div
contents based on that value and appends them into the container, but when I change the value again it keeps going, it doesn't reset.
The code is the following:
const select = document.getElementsByTagName('select')[0];
const container = document.getElementById('container');
select.onchange = () => {
for (let i = 0; i < Number(select.value); i++) {
let content = document.createElement('div');
content.classList.add('content');
container.appendChild(content);
}
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
height: 100vh;
}
.app {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: 12% 88%;
background: #5F9EA0;
}
select {
width: 60px;
height: 40px;
background: red;
color: #fff;
font-size: 24px;
border-radius: 10px;
outline: none;
}
#container {
width: 100%;
height: 100%;
background: darkcyan;
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.content {
width: 150px;
height: 150px;
border-radius: 15px;
background: darkgreen;
margin: 10px;
}
<div class="app">
<select>
<option>0</option>
<option>3</option>
<option>6</option>
<option>9</option>
</select>
<div id="container"></div>
</div>
How can I reset the contents before adding the other contents?