Lukas König
Lukas König

Reputation: 43

TypeError: table is null when adding row to table

I am Trying to create and add elements to a table.

function flaeche() {
    let tableID = "testTable";
    let x = document.createElement("TABLE");
    x.setAttribute("id", tableID);
    for (let argument of arguments) {
        let radius = ((argument*argument)*Math.PI).toFixed(2);
        addRow(argument,radius,tableID);
    }
}

function addRow(value, result, tableID){
    let table = document.getElementById(tableID);
    let row = table.insertRow(0);
    let cell1 = row.insertCell(0);
    let cell2 = row.insertCell(1);
    cell1.innerHTML = value;
    cell2.innerHTML = result;
}

If I try to run the code I get the following error: TypeError: table is null at addRow line 30:5 which corresponds to let table = document.getElementById(tableID); I really have no idea why it says so since I am fairly new to JavaScript. I appreciate your help.

Upvotes: 2

Views: 962

Answers (1)

Mark
Mark

Reputation: 92440

You are making a table element, but you aren't adding it to the page. You need to actually put the table somewhere in the DOM if you want to find it with document.getElementById() later. For example:

function flaeche() {
    let tableID = "testTable";
    let x = document.createElement("TABLE");
    x.setAttribute("id", tableID);

    // add table to the page somewhere
    // for example in the div named container
    let container = document.getElementById("container")
    container.appendChild(x)

    for (let argument of arguments) {
        let radius = ((argument*argument)*Math.PI).toFixed(2);
        addRow(argument,radius,tableID);
    }
}

function addRow(value, result, tableID){
    let table = document.getElementById(tableID);
    let row = table.insertRow(0);
    let cell1 = row.insertCell(0);
    let cell2 = row.insertCell(1);
    cell1.innerHTML = value;
    cell2.innerHTML = result;
}

flaeche(5, 6)
td {
  border: 1px solid #ddd;
  padding: 1em;
  
}
<div id="container"></div>

Upvotes: 2

Related Questions