I'm currently working on WebComponent
using plain HTML
and VanillaJS
. The objective is to provide a working collection of Components
for the company to use.
<template id="x-intranet-alert">
<div class="alert">
<p></p>
</div>
</template>
<script>
class IntranetAlert extends HTMLElement {
static get observedAttributes() {
return ['message', 'type', 'close']
}
constructor() {
super()
this.innerHTML = document.currentScript.ownerDocument.querySelector('#x-intranet-alert').innerHTML
}
attributeChangedCallback(attr, oldValue, newValue) {
switch(attr) {
case 'type':
this.querySelector("div").className = `alert ${newValue}`
break
// ...
}
}
}
customElements.define('intranet-alert', IntranetAlert);
</script>
This is working fine if I'm doing it in HTML
<intranet-alert type="info" message="Je suis une alert de type info" close="true"></intranet-alert>
But if I try to create it programmatically I have an error because document.currentScript.ownerDocument
is document
and not the components document.
let alert = new IntranetAlert()
alert.setAttribute("type", "danger")
alert.setAttribute("message", "Component créé dynamiquement")
document.querySelector("#alert").appendChild(alert)
How can I import the document so it works on both way?