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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With