Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda