Last active
November 15, 2024 15:57
-
-
Save hemanth/e6bb66141101b52a76fe to your computer and use it in GitHub Desktop.
Extend DOM elements ES6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SmartButton extends HTMLButtonElement { | |
constructor() {} | |
} | |
let sb = new SmartButton(); | |
document.body.appendChild(sb); | |
/* | |
I get the below error: | |
TypeError: Failed to execute 'appendChild' | |
on 'Node': parameter 1 is not of type 'Node'. | |
It needs a document.registerElement as well? :/ | |
But then what's the whole point of extending, it can just do a Object.create() | |
*/ |
and you will not be able to call your class with new
you must create it in DOM way:
document.createElement('smart-button');
or
insert in html
instead constructor you can use createdCallback()
class CustomElement extends HTMLElement {
// Fires when an instance of the element is created.
createdCallback() {
};
// Fires when an instance was inserted into the document.
attachedCallback() {
};
// Fires when an instance was removed from the document.
detachedCallback() {
};
// Fires when an attribute was added, removed, or updated.
attributeChangedCallback(attr, oldVal, newVal) {
};
}
document.registerElement('custom', CustomElement);
let element = document.createElement('custom');
document.body.appendChild(element);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you need to register your element
document.registerElement('smart-button', SmartButton);
https://www.polymer-project.org/1.0/articles/es6.html