0

I am trying to display all info from an array to a table. This is my javascript array:

JS

let tableUsers = [
    {name: "Jose", age: "22", Country: "Spain"},
    {name: "Jon", age: "25", Country: "France"},
    {name: "Jacob", age: "36", Country: "Italy"}
]
3
  • 1
    If you fix your indenting to match up with { .... } blocks, you'll see that rad is defined inside the for loop, but table.appendChild(rad) is outside the loop, so can't see it. (Even if you didn't have the error, you would only be adding a row once, when you want to add a row for each item.) Commented Jan 19, 2022 at 11:47
  • Ah, I see. When put the ´table.appendChild(rad)´ inside nothing is displayed. hmm Commented Jan 19, 2022 at 11:51
  • That's because you haven't put the table as a whole anywhere on the page. Presumably you wanted to put it inside the div you've selected into tableUsers. Commented Jan 19, 2022 at 11:54

1 Answer 1

1

I think you are misunderstanding of variable definition. In ES6, we use let keyword to define variable and is valid in the scope of bracket in which it is defined. So the code should be following.

let tableUsers = document.getElementById("tableDiv");

function drawTable(){
let table = document.createElement("table");
let tableHead = document.createElement("thead");
let colHeads = ["column1", "column2"];

for (let header of colHeads){
    let celle = document.createElement("th")
    celle.innerHTML = header;
    tableHead.appendChild(celle);
}
table.appendChild(tableHead)

let rad; // defined out of the for loop 

for(let x of info){
    rad = document.createElement("tr");

    let firstname = document.createElement("td");
    firstname.innerHTML = x.name.first;
    rad.appendChild(firstname);

    }

table.appendChild(rad)
}

drawTable()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.