Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prototypes on Custom Elements

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading