Search code examples
javascripthtmlinnerhtmlappendchild

Can't add new row to table


function load(){
    var row="<tr><td><select id=\"chooseclass\"><option value=\"math\">Math</option><option value=\"phys\">Physics</option><option value=\"lit\">Literature</option><option value=\"chem\">Chemistry</option><option value=\"bio\">Biology</option><option value=\"lang\">Language</option><option value=\"proj\">Project</option><option value=\"elec\">Elective</option></select></td><td><input id=\"choosemods\" type=\"text\" /></td><td><input id=\"choosegrade\" type=\"text\" /></td></tr>";
    var tablebody = document.getElementById("classestable");
    tablebody.innerHTML += "<tbody></tbody>";
    tablebody.getElementsByTagName("tbody").innerHTML = "";
    for(var i=0;i<15;i++){
        tablebody.getElementsByTagName("tbody").innerHTML += row;
    }
}

The code above runs fine except the contents of row does not get added to tbody.

console.log shows that the contents of row is valid html and there are no errors in the console. Why is that not being added?


Solution

  • getElementsByTagName returns a NodeList and you access it the first node using the index of the node

    I would change the code to the following

    var innerRow = "";
    
    for(var i=0;i<15;i++){
        innerRow += row;
    }
    
    tablebody.getElementsByTagName("tbody")[0].innerHTML = innerRow
    

    this way you only scanning the DOM once not 15 times