createElement counter button
by WebComponents
HTML
<script>
customElements.define(
"my-counter",
class extends HTMLElement {
constructor( ) {
// MDN is wrong, You CAN use JS before super(), just not 'this' scope related code
const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props);
super() // sets AND returns 'this' scope
.attachShadow({ mode: "open" }) // sets AND returns this.shadowRoot
.append( // not supported in IE, that is why all blogs use oldskool appendChild
createElement("style", {
textContent:
"*:not(style){font-size:200%;width:4rem;display:inline-block;text-align:center}" +
"button{height:4rem;border:none;border-radius:10px;background:seagreen;color:white}",
}),
createElement("button", {
onclick: _ => this.count--,
textContent: "-"
}),
this.p = createElement("p", {
textContent: 0
}),
createElement("button", {
onclick: _ => this.count++,
textContent: "+"
}),
) // append
}
set count(p) {
this.p.textContent = p
}
get count() {
return ~~this.p.textContent
}
},
)
</script>
<my-counter></my-counter>