Custom Elements in JavaScript 6
by Hasan Yousef
HTML
Here is some non-custom stuff.
<div id="placeholder"><p>Please wait, loading cool things<p></div>
<save-button data-text='click this'></save-button>
CSS
save-button > button{
color: orangered;
}
JavaScript
// Write JavaScript here
"use strict";
class SaveBtn extends HTMLElement {
constructor() {
super();
}
createdCallback(){
this.innerHTML = ""+
" <style> "+
" p { color: orange; } "+
" </style> "+
" <p>I'm in a custom element;.</p> "+
" <button id='btn'></button> "+
"";
var btn = this.querySelector('button');
btn.addEventListener('click',() => alert('The button '+btn.textContent+' had been clicked'));
}
attachedCallback(){
this.querySelector('#btn').textContent = this.btntext != null ? this.btntext : this.dataset['text'];
}
set properties(prop) {
this.btntext = prop.text;
}
get text() {
return this.textContent;
}
}
var MySaveBtn = document.registerElement("save-button", SaveBtn);
var myBtn = new MySaveBtn;
myBtn.properties={ text: 'click me' }; // or myBtn.text = 'click me';
document.querySelector('#placeholder').appendChild(myBtn);