Knockout.js containerless "foreach" not working with <table>

Syntaxknockout.js

Syntax Problem Overview


This code throws the error (in Chrome): "Cannot find closing comment tag to match: ko foreach: MyPlans":

<table>
  <!-- ko foreach: MyPlans -->
    <tr>
      <td>Test</td>
    </tr>
  <!-- /ko -->
</table>

If I use a list instead, everything works:

<ul>
  <!-- ko foreach: MyPlans -->
    <li>
      Test
    </li>
  <!-- /ko -->
</ul>

I would like to use the containerless foreach with a table. Is there something I'm doing wrong? Is it a bug?

Syntax Solutions


Solution 1 - Syntax

This is related to the fact that browsers insert tbody tags automatically, which creates a mismatch in the comments. The rendered output will look like:

<table>
  <!-- ko foreach: MyPlans -->
  <tbody>
    <tr>
      <td>Test</td>
    </tr>
  <!-- /ko -->
  </tbody>
</table>

Steve did put some work into trying to correct mismatched tags in KO, but the easiest thing for you to do is either add the tbody yourself or add the tbody and put your binding on it.

<table>
  <tbody data-bind="foreach: MyPlans">
    <tr>
      <td>Test</td>
    </tr>
  </tbody>
</table>

It is legal for a table to have multiple tbody tags, if necessary.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJagView Question on Stackoverflow
Solution 1 - SyntaxRP NiemeyerView Answer on Stackoverflow