A Portal web component for Elm

July 8, 2025 ยท View on GitHub

window.customElements.define("elm-portal", class extends HTMLElement { // Base custom element stuff constructor() { super(); this._targetNode = document.createElement('div'); }

connectedCallback() { document.querySelector(this.getAttribute("data-target-selector")).appendChild(this._targetNode); }

disconnectedCallback() { document.querySelector(this.getAttribute("data-target-selector")).removeChild(this._targetNode); }

// Re-implementations of HTMLElement functions get childNodes() { return this._targetNode.childNodes; }

replaceData(...args) { return this._targetNode.replaceData(...args); }

removeChild(...args) { return this._targetNode.removeChild(...args); }

insertBefore(...args) { return this._targetNode.insertBefore(...args); }

moveBefore(...args) { return this._targetNode.moveBefore(...args); }

appendChild(...args) { // To cooperate with the Elm runtime requestAnimationFrame(() => { return this._targetNode.appendChild(...args); }); } });