textElement

Create HTML Components using simple HTML Text strings.

Creating elements

Regular function usage

import { shadowOpen } from "./textElement.mjs";
const HTMLString = "<div>I am HTML</div>";
const SampleElementClass = shadowOpen(HTMLString);
globalThis.customElements.define("sample-element", SampleElementClass);

Tag function usage

import { shadowClosed } from "./textElement.mjs";
globalThis.customElements.define(
  "sample-element",
  shadowClosed`<div>I am HTML</div>`
);

shadowOpen vs shadowClosed

shadowOpen creates an element with an accessible shadowRoot.

globalThis.customElements.define(
  "open-element",
  shadowOpen`<div>I am open</div>`
);
//...
globalThis.console.log(
  globalThis.document.getElementsByTagName("open-element")[0].shadowRoot
); //Logs element

shadowClosed creates an element with an inaccessible shadowRoot.

globalThis.customElements.define(
  "closed-element",
  shadowClosed`<div>I am open</div>`
);
//...
globalThis.console.log(
  globalThis.document.getElementsByTagName("closed-element")[0].shadowRoot
); //Logs null

Composing elements

Use the slot element within the HTML string to allow for other HTML elements to be embedded.

globalThis.customElements.define(
  "composable-element",
  shadowOpen`<div><slot /></div>`
);
<composable-element> I'm dynamic content </composable-element>

Renders like:

<div>I'm dynamic content</div>

Named Slots

Used named slots to place multiple pieces content within an element.

globalThis.customElements.define(
  "composable-element",
  shadowOpen`<slot name="first" /><slot name="second" />`
);
<composable-element>
  <span slot="second">2nd</span>
  <span slot="first">1st</span>
</composable-element>

Renders like:

<div>
  <span>1st</span>
  <br />
  <span>2nd</span>
</div>

Styling Elements

Elements can be styled by adding a style tag to the HTML string.

Because the style tag exists within the shadowRoot, styles will only be applied within the element.

const RedTextClass = shadowOpen`<style>*{color:red}</style><slot />`;

Styling slotted elements

Slotted elements exist outside of the shadowRoot and can be styled outside of the element.

globalThis.customElements.define("red-element", RedTextClass);
<style>
  .blue {
    color: blue;
  }
</style>
<red-element>
  <span class="blue">This text is blue</span>
</red-element>

Using ::part() sudo-element

Parts of the element intended to be the target of external styles can be marked with the part attribute.

globalThis.customElements.define('stylable-element', shadowOpen`<div part=content> I'm stylable externally</div>`;
<style>
  stylable-element::part(content) {
    color: blue;
  }
</style>
<stylable-element />