0

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>?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
equanimity
  • 2,371
  • 3
  • 29
  • 53
  • Your selector cares nothing about tables. It's going to return the first tbody element it finds, regardless of its context. – isherwood Sep 16 '22 at 20:26
  • 1
    FYI, a body element is invalid inside a table. A document may only have one. – isherwood Sep 16 '22 at 20:27
  • @isherwood I'm pretty sure that's a typo for `` – Barmar Sep 16 '22 at 20:27
  • `querySelector` finds the **first** element that matches. Either use a more specific CSS selector string than `tbody` (Google for how to find the first element of type with querySelector), or use querySelectorAll to get multiple matches and figure it out in a loop – Andy Ray Sep 16 '22 at 20:28
  • I think the thing the OP is concerned about is whether the browser automaticlly adds `` to tables that don't have it, like they do when fixing up other HTML errors. I don't think this is a case where they do it. – Barmar Sep 16 '22 at 20:29
  • 1
    @isherwood I misread and thought they said "two don't have a ``" – Barmar Sep 16 '22 at 20:30
  • [All `table` elements have at least one `tbody` element silently added if not present in the source](https://stackoverflow.com/q/938083/215552), so your selector is likely to always return the first `tbody` of the first `table` element in source order. – Heretic Monkey Sep 16 '22 at 20:34
  • Coming back to my original question, should I then add an ID to the table (``), and also amend the `querySelector` to `document.querySelector('my-table')`?
    – equanimity Sep 16 '22 at 20:43
  • So use a better selector. Use an id or class or something of a parent. – epascarello Sep 16 '22 at 20:44

0 Answers0