I am working on the Etch A Sketch project on The Odin Project. I have created a grid by manipulating the DOM. I want to resize the grid by removing the old grid created and enter in a new one by prompting the user. I notice I cannot access any nodes I created since they are in the createGrid(). Is there any way to delete the created elements associated with my grid while keeping my loop intact?
I tried to have verticalBoxes.remove() in the resizeGrid() however I know it does not work because it is not in the global scope. I also tried removing the container within my resizeGrid() and creating a new one but there ends up being declaration issues due to there being duplicate container variables.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch A Sketch</title>
<link rel="stylesheet" href="styles.css">
<script src= "scripts.js" defer></script>
</head>
<body>
<h1>Etch A Sketch</h1>
<div id= "container"></div>
<div id= "grid-size">
<button type="confirm" id= "resize-button">Resize Grid</button>
</div>
</body>
</html>
#container {
margin: auto;
max-width: 500px;
max-height: 500px;
}
h1 {
text-align:center;
}
.row {
display:flex;
height: auto;
}
.column {
flex: 1;
width: 100%;
aspect-ratio: 1;
border: 1px solid black;
}
.resize-button {
display: inline-block;
width:50px;
height:50px;
}
let container = document.querySelector("#container");
const button = document.querySelector("#resize-button")
function createGrid(num) {
for (let i = 0; i < num; i++) {
let horizontalBoxes = document.createElement("div");
container.appendChild(horizontalBoxes);
horizontalBoxes.classList.add("row");
for (let y = 0; y < num; y++) {
let verticalBoxes = document.createElement("div");
horizontalBoxes.appendChild(verticalBoxes);
verticalBoxes.classList.add("column");
verticalBoxes.addEventListener('mouseover', colorChange);
}
}
}
function colorChange () {
this.style.backgroundColor = "black"
}
createGrid(16);
function resizeGrid(newSize) {
newSize = prompt("What size would you like the grid to be? (1-100)");
createGrid(newSize);
}
button.addEventListener('click', resizeGrid);
2
Answers
Simply empty the contents of
container
before inserting your new elements.See Remove all child elements of a DOM node in JavaScript for various ways to achieve this.
The example below uses
Wouldn’t replaceChildren() be an excellent fit for your use ?
Simply store the new nodes you create and then use replaceChildren to add them all while deleting the link between the parent and the old child nodes.
With this solution I believe your
createGrid()
function would look something like this :Note that
replaceChildren()
expects successive arguments and not a singular array of new children, hence the spread.