Element 'th' cannot be nested in element 'table'
Asked Answered
V

2

13

Given the following HTML, why do you get the error:

Validation (HTML5): Element 'th' cannot be nested in element 'table'

<table>
    <th>ID</th>
    <th>text header</th>
    <tr>
        <td>7</td>
        <td>text</td>
    </tr>
</table>
Vorticella answered 3/6, 2014 at 21:7 Comment(1)
<th> header cells must be defined within a table row (<tr>) just like <td>s.Googly
V
29

You cannot have the <th> element outside of a <tr>, the following snippet is valid

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>text header</th>
        </tr>
    </thead>
    <tbody>
    <tr>
        <td>7</td>
        <td>text</td>
    </tr>
    <tbody>
</table>

<th> Usage context https://developer.mozilla.org/en/docs/Web/HTML/Element/th

Permitted parent elements

A <tr> element.

Vorticella answered 3/6, 2014 at 21:7 Comment(2)
Should have been obvious really, given the structure of HTML tables and that everything has to be in a rowVorticella
I ran into this, and because the message didn't really say what it should have had in the parent elements (at least in the tool I was using), it wasn't immediately obvious. It should have been obvious sure, but everyone has their days.Physicist
H
0

With thead I was getting the similar warning. This is a razor page in Visual Studio.

<table>
    <thead>
        <th>Id</th>
        <th>Name</th>
    </thead>
    <tbody>
        @foreach(var customer in Model.Customers.Take(100))
        {
            <tr>
                <td>@customer.Id</td>
                <td>@customer.Name</td>
            </tr>
        }
    </tbody>
</table>

To mitigate that, I replaced th with tr as follows.

<table>
    <thead>
        <tr>Id</tr>
        <tr>Name</tr>
    </thead>
    <tbody>
        @foreach(var customer in Model.Customers.Take(100))
        {
            <tr>
                <td>@customer.Id</td>
                <td>@customer.Name</td>
            </tr>
        }
    </tbody>
</table>
Herrod answered 14/1, 2022 at 13:54 Comment(1)
I think in your case, you just needed to surround all your <th> elements in a row. I have updated my answer to illustrate thisVorticella

© 2022 - 2024 — McMap. All rights reserved.