简体   繁体   中英

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.

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
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM