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

113
Visualizações
JS create new element then edit the html in that new element

I am basically trying to go through an array of arrays and create a new div element for each array item on the array and then add some code to the new div element created. I get Cannot set properties of null (setting 'innerHTML') error message which I understand to mean the JS does not recognise the div element when it is run but surely if I just created it in the line before it should exist by the time that line is executed. Sample code below:

for (var elem in ArrayOfArray){
            document.createElement('div').setAttribute('id', elem[1]);
            document.getElementById(elem[1]).innerHTML = "hello (or some other code)";
        }

Does anyone know why this doesn't work? TIA

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

0

document.getElementById searches the document for an element with a given ID.

You've created an element, set an attribute on it, and then discarded it. You haven't kept any references to it and you haven't added it to the document.

It isn't in the document for getElementById to find.


const element = document.createElement('div');
element.setAttribute('id', elem[1]);
document.body.appendChild(element);
document.getElementById(elem[1]).innerHTML = "hello (or some other code)";

But since you need to keep a reference to the element in order to do that, you can skip dealing with IDs entirely.

const element = document.createElement('div');
document.body.appendChild(element);
element.innerHTML = "hello (or some other code)";
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