0

When using LitElement to render data dynamically, the browser inserts tbody all the time negating any effort to "group" table rows.

  render() {
    return html`
    <table style="border-collapse:collapse;border:solid 1px #666;">
      ${this.rows.map((row)=>{
        
        var disp= html`
        ${(row=="FOUR")?html`</tbody>`:''}
        ${(row=="TWO")?html`
          <tbody style="border:solid 2px #F00; border-collapse:separate;">
          <tr>
            <td>SOME HEADER</td>
          </tr>
        `:''}
        <tr>
          <td>${row}</td>
        </tr>
        `
        return disp;
      })}

    </table>
    `;
  } //render()

  constructor() {
    super();
    this.rows = ['ONE','TWO','THREE','FOUR'];
  }

The result is the tbody is closed immediately after the closing tr of "SOME HEADER" instead of the tbody being closed after the tr "FOUR" which is what we want in this case.

It looks like the browser does this by itself because it always wants to insert a tbody whenever a tr is written to the DOM? So I suspect this would happen to any framework that renders data dynamically - but have not verified this.
I assume this is not going to be "fixed" anytime soon.

That being the case, anyone have a suggestion on how to group tr's together in a block in this case?

Thanks!

user3757849
  • 199
  • 2
  • 14

1 Answers1

0

If you have an unclosed <tbody> in a document fragment the browser will close it for you.

Instead nest the <tr> you want to group inside a template that holds both the <tbody> and closing </tbody>:

const groups = //process this.rows into groups

return html`
<table style="border-collapse:collapse;border:solid 1px #666;">
    ${groups.map(g => html`

    <tbody style="border:solid 2px #F00; border-collapse:separate;">
        <tr><th>${g.name}</th></tr>

        ${g.rows.map(r => html`
        <tr><td>${r}</td></tr>`)}

    </tbody>`)}
</table>`;
Keith
  • 150,284
  • 78
  • 298
  • 434