Simon Palmgren
Simon Palmgren

Reputation: 3

Iterate and append to table

Hello i am trying to append some strings from an array to an table. I want every array item to have its own tr element.

The things i have tried so far is this:

const body = document.body
const table = document.createElement('table')
const tr = document.createElement('tr')
const th = document.createElement('th')
const form = document.createElement('form')
const  label = document.createElement('label')

table.innerHTML
body.append(table)

tr.innerHTML
table.append(tr)

const thText = ["ID", "First name", "Last name", "Email", "Phone number", "Actions"]

thText.forEach((text)=>{
  th.innerHTML = text
  tr.append(th);
})

When console.log(th) i get <th> Actions </th> 6 times. but the only thing that is rendered is Actions once.
Would love to get some help. Thanks :)

Upvotes: 0

Views: 582

Answers (2)

skaz
skaz

Reputation: 301

There's a few different ways to do this. Here's an example of one way. This method does a few things differently then your example.

  • It creates and uses a thead element for proper table formatting.
  • It uses a basic for loop method.
  • It creates a new th element for each header label in the array, then it appends it to the tr element.
  • It uses textContent instead of innerHTML

const headerLabels = ["ID", "First name", "Last name", "Email", "Phone number", "Actions"]
const body = document.body
const table = document.createElement('table')
const thead = document.createElement('thead')
const tr = document.createElement('tr')

thead.append(tr)
table.append(thead)
body.append(table)

for (let i = 0; i < headerLabels.length; i++)  {
    let th = document.createElement('th')
    th.textContent=headerLabels[i]
    tr.append(th)
}
td, th {
    border: 1px solid #ddd;
    padding: 8px;
}
  
tr:nth-child(even) {
 background-color: #f2f2f2;
}
  
th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: #4CAF50;
    color: white;
}
<body>
    <script src="main.js"></script>
</body>

Upvotes: 0

Brandon Hill
Brandon Hill

Reputation: 1900

You're only creating one th element. You'd need to create one for each iteration, so, within the loop:

thText.forEach(text => {
  const th = document.createElement('th')
  th.innerHTML = text
  tr.append(th)
})

Upvotes: 1

Related Questions