I was wondering if there is a way to add elements generated by innerHtml. It's not that hard to do with createElement but for me innerHtml feels just more logical and easy. I made a example code to show my problem:
Create element:
const grid = document.querySelector('.grid')
let squares = []
function createGrid() {
for (let i=0; i < 100; i++) {
const square = document.createElement('div')
square.classList.add('square')
grid.appendChild(square)
squares.push(square)
}
}
function hideSquare(){
let random = Math.floor(Math.random()*100)
squares[random].style.display = "none"
}
innerHtml:
const grid = document.querySelector('.grid')
let squares = []
function createGrid() {
for (let i=0; i < 100; i++) {
grid.innerHtml += `<div class="square"></div>`
// ???
}
}
function hideSquare(){
let random = Math.floor(Math.random()*100)
squares[random].style.display = "none"
}
You can use lastChild to get the div you just inserted (note I added the id in the code below just to visualize the order), also, it is innerHTML not innerHtml:
const grid = document.querySelector('.grid');
let squares = [];
function createGrid() {
for (let i=0; i < 5; i++) {
grid.innerHTML += `<div id="square-${i+1}" class="square"></div>`;
squares.push(grid.lastChild);
}
}
createGrid();
console.log(squares);
<div class="grid"></div>
Here is my approach wirh .innerHTML:
function createGrid(n) {
// assign the innerHTML only ONCE:
grid.innerHTML = [...Array(n)].map((_, i) => `<div class="square">${i}</div>`).join("\n");
return [...grid.querySelectorAll(".square")] // return all DOM elements in an array
}
function shfl(a) { // Durstenfeld shuffle
for (let j, i = a.length; i > 1;) {
j = Math.floor(Math.random() * i--);
if (i != j)[a[i], a[j]] = [a[j], a[i]]
}
return a
}
const grid = document.querySelector('.grid');
const squares = shfl(createGrid(30));
document.querySelector("button").onclick = () => squares.length && (squares.pop().style.visibility = "hidden");
.square {
height: 20px;
width: 20px;
display: inline-block;
background-color: #ddd;
margin: 4px;
padding: 10px;
text-align: right
}
<button>hide a square</button>
<div class="grid"></div>
The original hideSquare() function had the problem, that a hidden square could have been chosen again for hiding, giving the user the impression that the click "didn't work". By shuffling the array of all squares once and then hiding the elements one after the other this problem is avoided.