Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create HTML Element with ES6

For an application i want to create Object-Based components in ES6.

On the normal way, you can create Elements as follow:

var element = document.createElement('YourElement');
element.innerHTML = 'Content';
document.querySelector('body').appendChild(element);

How i can create these in ES6 like:

export default class Container extends HTMLDivElement {
    constructor() {
        super();
        this.innerHTML = 'Content';
    }   
}

With these example?

var container = new Container();
document.querySelector('body').appendChild(container);

My idea is, to create an -only JavaScript- UI Framework, without using "native" HTML snippets...

like image 269
Adrian Preuss Avatar asked Oct 12 '25 04:10

Adrian Preuss


1 Answers

<div class='body'>

</div>

<script>
class Container extends HTMLElement {
    constructor() {
        super();
        console.log( 'Constructed' )
    }   
    connectedCallback() {
      console.log('Callback');
      this.innerHTML = "Content";
    }
}
customElements.define('my-contain', Container);
let container = new Container();
document.querySelector('.body').appendChild(container);
</script>

You need to register your Component with the CustomElementRegistry below your Class definition and utilize the connectedCallback().

export default class Container extends HTMLDivElement {
    constructor() {
        super();
        this.innerHTML = 'Content'; // Does Nothing
    } 
    connectedCallback() { // Fires when attached
      console.log('Callback');
      this.innerHTML = "Content";
    }  
}

customElements.define('my-contain', Container, { extends: "div" });

LIFECYCLE HOOKS OF CUSTOM COMPONENTS enter image description here

More info on CustomElementRegistry here: MDN CustomElementRegistry

More info on implementation of such here: MDN Using Custom Elements

like image 157
NSTuttle Avatar answered Oct 14 '25 21:10

NSTuttle