javascripthtmlweb-componentx-tag

The right way to create custom sub-elements with X-Tag


So I know the x-tag web component library enables you create custom elements that appear in HTML like this:

<x-my-custom-element>my content</x-my-custom-element>

However, what if I wanted to create multiple custom sub-elements, like this:

<x-my-custom-element>
    <x-my-custom-element-child>
        <x-my-custom-element-grandchild></x-my-custom-element-grandchild>
    </x-my-custom-element-child>
</x-my-custom-element>

Is the right way to simply call xtag.register() three times, like so:

xtag.register('x-my-custom-element', {...});
xtag.register('x-my-custom-element-child', {...});
xtag.register('x-my-custom-element-grandchild', {...});

Also, is there any way to force a sub-element to always be a child of another element? In other words, this would work:

<x-my-custom-element-parent>
    <x-my-custom-element-child></x-my-custom-element-child>
</x-my-custom-element-parent>

but this wouldn't:

<x-my-custom-element-child>
    <x-my-custom-element-parent></x-my-custom-element-parent>
</x-my-custom-element-child>

Solution

  • Because your custom element names are valid (contain a "dash" - character), you would only need to register them with xtag.register() if you need to add functionality, attributes, default content, shadow DOM, etc. Elements with unrecognized but valid names will simply be HTMLElement objects. Elements with unrecognized and invalid names will be HTMLUnknownElement objects.

    // valid custom element name
    document.createElement('foo-bar') instanceof HTMLElement; // true
    
    // invalid custom element name
    document.createElement('foobar') instanceof HTMLUnknownElement; // true
    

    You can read the WHATWG Spec for HTMLUnknownElement here.

    I don't know of any way to force element hierarchy. Standard HTML elements don't enforce this. For example, you can do <li><ul></ul></li> and <source><video></source>. The elements simply don't function when used improperly like this.