Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
Adding elements generated by innerHtml to array

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"
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!