Search code examples
javascripthtmldoctypescript-tag

Can I have <SCRIPT> tag inside <TABLE>?


I got to have a tag inside a table because PHP writes a code there that adds stuff to an earlier created Javascript array. However, I get a validation error (4.01 strict).

Is there any way I can do this or is it simply forbidden to keep a script like this:

<TABLE>
    <TR>
      <SCRIPT></SCRIPT>
        <TD>
        </TD>
    </TR>
</TABLE>

(is this better maybe?):

<TABLE>
    <TR>
        <TD>
         <SCRIPT></SCRIPT>
        </TD>
    </TR>
</TABLE>

Change doctype? What do you think?


Solution

  • Ever since the release of HTML 5, it is legal to have a <script> inside most kinds of table element, including trs.

    At https://html.spec.whatwg.org/multipage/tables.html, you can see that the content models for table, caption, tbody, thead, tfoot, tr, td and th all include either "Flow content" or "one or more script-supporting elements". At https://html.spec.whatwg.org/multipage/dom.html#flow-content-2 and https://html.spec.whatwg.org/multipage/dom.html#script-supporting-elements-2 respectively, we see that scripts are defined to be both flow content and script-supporting elements, and are therefore allowed within any of those elements.

    The notable exceptions are colgroups (which can only contain cols and templates) and cols (which can't have content). You can't put a script inside either of those.

    This means that the asker's example HTML with a script inside a tr...

    <TABLE>
        <TR>
          <SCRIPT></SCRIPT>
            <TD>
            </TD>
        </TR>
    </TABLE>
    

    ... is now valid, which you can confirm at https://html5.validator.nu.

    Gumbo's answer, stating that scripts are allowed inside tds but not trs, was correct for HTML 4, but is now outdated.