Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a table row with custom web components

I'm learning how to use custom Web components. I try to create a table row with a custom component. Here is the HTML:

<table border="2">
    <tbody>
        <table-row></table-row>
        <table-row></table-row>
    </tbody>
</table>

Here is the JavaScript:

// Create a class for the element
class TableRow extends HTMLElement {

  constructor() {
    // Always call super first in constructor
    super();
  }

  connectedCallback() {
        let tr = document.createElement('tr')
        let td = document.createElement('td')
        td.textContent = "Row content";
        tr.append(td);
        this.append(tr);
  }
}

customElements.define("table-row", TableRow);

Here is a JSFiddle: https://jsfiddle.net/Imabot/c92fye8d/1/

As you can see, it does not work as expected.

Am I doing something wrong?

Generally speaking, when building a custom component, should we fill or replace the custom tags <table-row></table-row>?

// Create a class for the element
class TableRow extends HTMLElement {

  constructor() {
    // Always call super first in constructor
    super();
  }

  connectedCallback() {
        let tr = document.createElement('tr')
        let td = document.createElement('td')
        td.textContent = "Row content";
        tr.append(td);
        this.append(tr);
  }
}

customElements.define("table-row", TableRow);
<table border="2">
    <tbody>
        <table-row></table-row>
        <table-row></table-row>
    </tbody>
</table>
like image 317
Fifi Avatar asked Sep 19 '25 11:09

Fifi


1 Answers

you cannot use custom tags in a table and its also not recommended to do so.

What u can do is to define a as a custom row like in this example:

class CustomTableRow extends HTMLTableRowElement {
  constructor() {
    super(); // Always call super first in constructor
    // Your custom initialization
  }

  connectedCallback() {
    let td = document.createElement('td');
    td.textContent = "Row content";
    this.appendChild(td);
  }
}

customElements.define('custom-table-row', CustomTableRow, { extends: 'tr' });
<table border="2">
    <tbody>
        <tr is="custom-table-row"></tr>
        <tr is="custom-table-row"></tr>
    </tbody>
</table>
like image 141
julian gommer Avatar answered Sep 21 '25 02:09

julian gommer