How can I get the body of a table using document.querySelector when there is more than one table on a page?

Viewed 35

I have three Bootstrap tables on a page (all of which are of class=table and none of which currently has an ID).

I have the following JavaScript function which I want to use to build a table:

function createTable(data) {
    const tableBody = document.querySelector('tbody');

    for (let i = 0; i < data.length; i++) {
        let tr = document.createElement('tr');
        tr.innerHTML = `<td>${data[i].id}</td>
        <td>${data[i].firstName}</td>
        <td>${data[i].lastName}</td>
        <td>${data[i].age}</td>`
        tableBody.append(tr)
    }
}

Two of the tables on my page have a <body> tag and only one of the tables has a <tbody> tag.

Question: in the above function, should I use an ID for document.querySelector? Or, will it "know" that it should only look at the only table that has <tbody>?

0 Answers
Related