Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda