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

108
Views
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 answers
Answer question

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 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!