DonC22
DonC22

Reputation: 21

How do I append results of for loop to table?

I have an array:

let items = document.getElementsByClassName('class-name')

for (let i = 0; i < items.length; i++ ) {
    status = items[i].innerText;
    console.log(status)
}

This returns either "SOLD" or "" depending on whether the item has been sold or not (it's an e-commerce page I'm looking at).

How do I append these results to a table?

I need a table with each item and whether it's been sold or not.

Upvotes: 0

Views: 103

Answers (2)

MrCodingB
MrCodingB

Reputation: 2314

you can create a table object via document.createElement('table') then create a new table row for each element via document.createElement('tr') after that you can "fill out" the tr and append it to the table via element.appendChild(childToAppend). You can also append td elements to the tr.

Upvotes: 1

Mister Jojo
Mister Jojo

Reputation: 22335

this way

const myTable = document.body.appendChild(document.createElement('table'))

document.querySelectorAll('.class-name').forEach( status => {
  let newRow = myTable.insertRow()
  newRow.insertCell().textContent = status.textContent
}

Upvotes: 2

Related Questions