ObiHill
ObiHill

Reputation: 11886

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>

Upvotes: 1

Views: 350

Answers (2)

jpec
jpec

Reputation: 460

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.

Upvotes: 3

Supersharp
Supersharp

Reputation: 31219

You cannot register 3 different custom elements with the same prototype.

So you'll need to create 3 different prototypes, for example with Object.create():

protoChild = Object.create( protoParent )
protoGrandchild = Object.create( protoChild )

Then call regsiter() method.

Regarding your second question, you'll need to control yourself the content of your custom element, when the element is created of attached.

Upvotes: 1

Related Questions