Which DOM elements can be child of tr?

后端 未结 4 1559
遥遥无期
遥遥无期 2020-11-30 14:57

I have problem becouse I want to surround some of td inside tr so I need to know.

Which DOM elements can be child of tr? (I know div<

相关标签:
4条回答
  • 2020-11-30 15:23

    The HTML spec states:

    Permitted contents

    Zero or more of: one td element, or one th element

    <tr> elements can contain only <td>s and <th>s.

    0 讨论(0)
  • 2020-11-30 15:32

    The situation is very similar to that of ul which I have described in detail at: Can we use any other TAG inside <ul> along with <li>? so I recommend you read that first.

    Notably, the less obvious point is that ASCII whitespace does not form text nodes, while any non-whitespace characters forms and illegal text node, which cannot be children of table.

    Then, in the "Content model" of tr in the current standard https://html.spec.whatwg.org/multipage/tables.html#the-table-element we see:

    Content model: Zero or more td, th, and script-supporting elements.

    0 讨论(0)
  • 2020-11-30 15:34

    If the question is about a DOM tree constructed from an HTML document that conforms to HTML specifications, then the answer is td and th, as explained in paxdiablo’s answer.

    But you can modify a DOM tree as you like, in scripting. For example:

    <!doctype html>
    <table border>
    <tr><td>foo <td>bar
    </table>
    <script>
    var p = document.createElement('div');
    p.innerHTML = 'Hello world!';
    document.getElementsByTagName('tr')[0].appendChild(p);
    </script>
    

    This will make a div element a child of a tr element. You could even put create some td elements and make them children of the div element.

    Whether this makes sense and whether it might confuse browsers is a different issue. And browsers will not parse normally HTML markup where e.g. tr element contains a div element as a child – parsers are not prepared to handle such cases. Grouping td elements (in any other way than making them children of a tr) is not possible in HTML markup. But in the DOM, you can create odd trees.

    If just want to deal with some td elements in a special way, give them a class.

    0 讨论(0)
  • 2020-11-30 15:41

    W3C specify this stuff. For tr, you can find it here. Basically, only th and td elements can be direct contents of tr.

    If you want other stuff inside your table, it has to go inside the td or th elements. For example, td can contain flow elements, including div.

    0 讨论(0)
提交回复
热议问题