Search code examples
javascriptknockout.jsjavascript-databinding

knockout:foreach with table columns inserts extra TR


A jsfiddle explains the problem. I want to use knockout:foreach to generate a list of column headers (<th> tags) for a table. But if you inspect the DOM, you can see that a <tr> is inserted around each <th>, which causes the column headings to all stack up above the leftmost column, instead of displaying one column header above the corresponding table cell.

I thought maybe the containerless syntax would be my friend, but here I am trying it in another jsfiddle and it does not work; if you open the javascript console you will see that the comment closing the foreach loop cannot be found (there are other SO questions about this particular issue but their solutions did not work for me).


Solution

  • You need to wrap your TH elements in a single TR instead of having the browser guess at where to put them.

    <thead>
      <tr data-bind="foreach:columns">
        <th data-bind="text: $data.field_name"></th>
      </tr>
    </thead>