Search code examples
htmlcustom-element

Can I use standard attributes in custom HTML elements?


Can I use standard attributes in custom elements(if they extend just HTMLElement)? Or I have to use data- custom attributes for them?


Solution

  • Section 4.13.3 of the HTML spec contains a list of the attributes that can be used with autonomous custom elements (ones that typically extend HTMLElement rather than some other existing element):

    Content attributes:
    Global attributes, except the is attribute
    form, for form-associated custom elements — Associates the element with a form element
    disabled, for form-associated custom elements — Whether the form control is disabled
    readonly, for form-associated custom elements — Whether to allow the value to be edited by the user
    name, for form-associated custom elements — Name of the element to use for form submission and in the form.elements API
    Any other attribute that has no namespace (see prose).

    Notably, custom elements can have any attribute names you desire, but with the exception of the ones listed above, these attributes won't have any of the special behavior you would expect from built-in elements if they happen to correspond to familiar attributes (such as type). You'll need to define this behavior yourself, of course.

    You only need to use custom data attributes when extending a built-in element and wanting to repurpose the name of an existing attribute.