Custom Element (HTMLElement) allowed as child of list (<ul> and <ol>)?

Viewed 84

I figure this is not allowed:

<ul>
  <my-li>
    #shadow-root
    <li>
      <span>hello!</span>
    </li>
  </my-li>
</ul>

But what can we do to not break semantics? I know that elements other than HTMLElement would exist, but Safari is not okay with this being the case. What would be the best solution to achieve a proper HTML semantic?

2 Answers

Custom elements can customize existing elements. If you're wanting to create a custom list item element, you should probably extend the existing one. This will allow you to validly place it as a child of an unordered list element.

When you're constructing a custom element, you can tell it to extend an existing element like so:

class MyLI extends HTMLLIElement {
  constructor() {
    super()
    ...
  }
}

customElements.define('my-li', MyLI, { extends: 'li' })

To use it, you would still use a regular, semantic, syntactically correct list item element, but you tell the browser it's an instance of a custom element with the is attribute.

<ul>
  <li is="my-li">
    #shadow-root
    <span>hello!</span>
  </li>
</ul>

If you are looking for validating on semantic use of HTML elements, then you can do that here

Related