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

140
Visualizações
Using Javascript to embed an onClick event to an HTML div

I'm trying to make an interactable and configurable grid using divs as their cells.

To first give a bit of context on this part of the code, I'm basically just repeating td's in HTML output then appending a specific amount of divs into the td's/rows (cellID is just a method for decorating the div names);

var table, row, div;
table = document.createElement('table');
for (var i=0; i < rows; i++)
{
    row = document.createElement('td');
    row.id = "row-" + i;
    for (var j=0; j < cols; j++)
    {
        div = document.createElement('div');
        div.id = cellID(i, j);
        row.append(div);
    }
    table.append(row);
}

Let's say that: -rows = 4 and -cols = 2 | The output result on the user's end would be this :

Example of what would be shown for a 2x4 grid

Now my current problem that I'm trying to figure out is how to make every repeated div be given the onClick() event so that an event occurs when you click on the boxes, here is what I tried to make this work :

  1. div.addEventListener("click", null); //This part didn't work for me, though to be honest, I don't really know what to replace the null with
  2. div.getElementById(div.id).onclick = function() { OnClick() }; (OnClick is a test method to see if it works, however this one just rejects an error, saying that "div.getElementById" is not a function, so I don't know what's up with that.)

These things I tried were all things that had been recommended throughout, but I don't know what else could make it work.

What do you think the problem may be there?

-
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

div.addEventListener() should work.

But you need to create valid DOM structure. Rows are tr, cells are td. You can put the div in the td, or just use the td directly.

let rows = 2,
  cols = 4;
var table, row, div;
table = document.createElement('table');
for (var i = 0; i < rows; i++) {
  row = document.createElement('tr');
  row.id = "row-" + i;
  for (var j = 0; j < cols; j++) {
    let cell = document.createElement("td");
    div = document.createElement('div');
    div.id = cellID(i, j);
    div.addEventListener("click", function() {
      console.log('Clicked on', this.id);
    });
    div.innerText = div.id;
    cell.append(div);
    row.append(cell);
  }
  table.append(row);
}
document.body.appendChild(table);

function cellID(i, j) {
  return `cell-${i}-${j}`;
}

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