Home > Software engineering >  Prototypes on Custom Elements
Prototypes on Custom Elements

Time:12-19

Suppose I have a custom HTML element tag <custom-table> with an attribute tableVal="10".

I would like to easily fetch the tableVal without using .getAttribute() (since I'm creating a public API that is easy-to-use).

Here's what I'm trying to do:

var customElement = document.querySelector('custom-table');
console.log(customElement.val)

Output: undefined
Expected Output: 10

This is my current try:

Object.setPrototypeOf(customElements.prototype, val.prototype)
function val(){
    return this.getAttribute("tableVal")
}

Any idea or approaches through which I can achieve this?

CodePudding user response:

There are a couple of ways to do this (see the MDN documentation on writing custom elements), but one is to create a class for your custom element with an accessor val property, and use that class when registering your custom element:

class CustomTable extends HTMLElement {
    get val() {
        return this.getAttribute("tableVal");
    }
}
customElements.define("custom-table", CustomTable);

Live Example:

<!-- Defining the custom element -->
<script>
class CustomTable extends HTMLElement {
    get val() {
        return this.getAttribute("tableVal");
    }
}
customElements.define("custom-table", CustomTable);
</script>

<!-- Using it in HTML -->
<custom-table tableVal="10"></custom-table>

<!-- Testing the property -->
<script>
const table = document.querySelector("custom-table");
console.log(table.val); // 10
</script>

  • Related