javascriptarraysarrayofarrays

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


Solution

  • 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)";