Are custom elements valid HTML5?
Asked Answered
M

12

207

I've been unable to find a definitive answer to whether custom tags are valid in HTML5, like this:

<greeting>Hello!</greeting>

I've found nothing in the spec one way or the other:

http://dev.w3.org/html5/spec/single-page.html

And custom tags don't seem to validate with the W3C validator.

Married answered 23/3, 2012 at 18:59 Comment(8)
You might not want to put too much stock in an HTML5 article written more than 4.5 years ago.Urgency
Crockford's article is an odd one. The important sentence is "This is my proposal for a kinder, gentler HTML 5". In other words, this is not the HTML5 we know today, but a proposal for a different HTML 5 as a successor to HTML 4. Odd, because it is dated November 2007, when the W3C had already been working on HTML5 for nearly a year. His use of the word "allowed" here is confusing. Custom tags have never been "conforming"/"valid", but browser parsers continue to work in their presence. Anyway, Crockford's proposal gained no traction at all. Barely any part of it is incorporated into HTML5.Seymore
Custom elements are becoming first class now that the emerging W3 standard for Web Components Custom Elements is beginning to land in Firefox and Chrome: dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/custom/…Ludovika
As for Douglas Crockford, I'm tempted to believe everything he says.Piker
w3.org/TR/components-intro/#defining-a-custom-elementLeland
Web browser support table for custom elements caniuse.com/#feat=custom-elementsVantassel
related: Proper way to apply CSS to HTML5 custom elementsPuppis
As I pointed out in my answer to a similar question, some browsers do not respond well to making up your own tag names. (In the example, the arbitrary ones look OK in Chrome and Firefox, but not in IE and Edge.)Darceldarcey
U
182

The Custom Elements specification is widely implemented today as part of Web Components. It provides a means to register custom elements in a formal manner.

Custom elements are new types of DOM elements that can be defined by authors. Unlike decorators, which are stateless and ephemeral, custom elements can encapsulate state and provide script interfaces.

Custom elements is a part of a larger W3 specification called Web Components, along with Templates, HTML Imports, and Shadow DOM.

Web Components enable Web application authors to define widgets with a level of visual richness and interactivity not possible with CSS alone, and ease of composition and reuse not possible with script libraries today.

However, from this excellent walk through article on Google Developers about Custom Elements v1:

The name of a custom element must contain a dash (-). So <x-tags>, <my-element>, and <my-awesome-app> are all valid names, while <tabs> and <foo_bar> are not. This requirement is so the HTML parser can distinguish custom elements from regular elements. It also ensures forward compatibility when new tags are added to HTML.

Some Resources

Urgency answered 23/3, 2012 at 19:8 Comment(4)
@Urgency if you "only" need support for custom elements, you might want to opt-in "only" for the Custom element polyfill webcomponents.org/polyfills/custom-elements. That's because "Polymer uses the polyfills from webcomponents.js", and one of them is this Custom element polyfill. This is mentioned in the Polymer web browser compatibility pageVantassel
@Urgency To clarify any doubt: "Sometimes there is some confusion regarding Web Components and Google Polymer. Polymer is a framework that is based on Web Components technologies. You can make and use Web Components without Polymer." see developer.mozilla.org/en-US/docs/Web/Web_ComponentsVantassel
The name of a custom element must contain a dash (-) but the tag in the question (greeting) does not; is it still a custom element?Mascle
Please note that using x- and polymer- as a web component name prefix is undesirable. See webcomponents.github.io/articles/how-should-i-name-my-elementAnacreontic
S
26

It's possible and allowed:

User agents must treat elements and attributes that they do not understand as semantically neutral; leaving them in the DOM (for DOM processors), and styling them according to CSS (for CSS processors), but not inferring any meaning from them.

http://www.w3.org/TR/html5/infrastructure.html#extensibility-0

But, if you intend to add interactivity, you'll need to make your document invalid (but still fully functional) to accomodate IE's 7 and 8.

See http://blog.svidgen.com/2012/10/building-custom-xhtml5-tags.html (my blog)

Seringapatam answered 17/10, 2012 at 14:2 Comment(8)
Looks like you did not read that entire section. Not only is it mostly about attributes, it even strongly discourages customization there.Rhodia
Repeating my other comments, yes, I'm sorry I didn't know to indicate it's my blog. I assumed that much was obvious. The article is directly relevant though. And I'll add, it's not meant to serve as a reference to back up any "claim" I've put forth, but to show in longer format how to do it so it works.Seringapatam
The point is simply this: the specification explicitly allows these things. And in most contexts of discouraging behavior, the specification is pretty clearly speaking to user-agent vendors, not HTML authors.Seringapatam
This statement quoted hereabove appears to have been removed in the most recent version of w3.org/TR/html5/introduction.html#extensibility. So far, I still can't find any documentation on whether the use of non-hyphenated custom HTML elements can be valid or not or whether you need JS statements to validate hyphenated custom HTML elements (html5rocks.com/en/tutorials/webcomponents/customelements).Latinism
@JohnSlegers Yeah, it looks like the documentation and/or the anchoring was rearranged a bit. I've updated the link. The quote in my answer is located near the bottom of the linked-to Extensibility section.Seringapatam
@Seringapatam : So you need explicitly namespaced elements to get custom elements to work nicely with IE<9, right? So they are rendered and processed but technically aren't "valid" HTML, right? Or are they? * confused *Latinism
@john right. adding namespaces to HTML isn't technically valid. But, it works. ... Of course, this is an old enough post that maybe ie <9 is irrelevant to most readers anyway.Seringapatam
It is present in the HTML Living Standard in section "2.1.10 Extensibility". I think this answer is the right one for the OP. No need for custom elements to explain the presence of greeting. But maybe I misunderstood.Bergmann
S
16

N.B. The answer below was correct when it was written in 2012. Since then, things have moved on a bit. The HTML spec now defines two types of custom elements - "autonomous custom elements" and "customized built-in elements". The former can go anywhere phrasing content is expected; which is most places inside body, but not e.g. children of ul or ol elements, or in table elements other than td, th or caption elements. The latter can go where-ever the element that they extend can go.


This is actually a consequence of the accumulation of the content model of the elements.

For example, the root element must be an html element.

The html element may only contain A head element followed by a body element.

The body element may only contain Flow content where flow content is defined as the elements: a, abbr, address, area (if it is a descendant of a map element), article, aside, audio, b, bdi, bdo, blockquote, br, button, canvas, cite, code, command, datalist, del, details, dfn, div dl, em, embed, fieldset, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, i, iframe, img, input, ins, kbd, keygen, label, map, mark, math, menu, meter, nav, noscript, object, ol, output, p, pre, progress, q, ruby, s, samp, script, section, select, small, span, strong, style (if the scoped attribute is present), sub, sup, svg, table, textarea, time, u, ul, var, video, wbr and Text

and so on.

At no point does the content model say "you can put any elements you like in this one", which would be necessary for custom elements/tags.

Seymore answered 24/3, 2012 at 3:20 Comment(6)
Ok, so we can assume that's if custom elements aren't mentioned, then they're also not permitted. That seems fair enough.Married
This answer is now invalid, the emerging W3 Web Components Custom Elements standard is beginning to land in browsers now: dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/custom/…Ludovika
@Ludovika - Actually no. The HTML5 or later standard will still need updating in some way to allow such custom elements to become part of its content model. It's interesting news though. Which browsers can I use them on?Seymore
@Alochi - obviously any other specs with old language will need to be updated to reflect this new reality, but HTML is a living standard, and does not block other specs - the updates will be made once we move to the next stages of the standard track. You can play around with native implementations of Web Components in Chrome Canary, and soon in Firefox Aurora. Additionally, there are polyfills available for 3 of the 4 Web Components specs that work very well in all of today's moder browsers - this includes the Custom Elements spec/features.Ludovika
So custom elements can be put in certain places? Or are you saying they are not permitted at all?Kati
@Kati - Things have moved on a bit since 2013. The HTML spec now defines two types of custom elements - "autonomous custom elements" and "customized built-in elements". The former can go anywhere phrasing content is expected; which is most places inside body, but not e.g. children of ul or ol elements, or in table elements other than td, th or caption elements. The latter can go where-ever the element that they extend can go.Seymore
L
15

Basic Custom Elements and Attributes

Custom elements and attributes are valid in HTML, provided that:

  • Element names are lowercase and begin with x-
  • Attribute names are lowercase and begin with data-

For example, <x-foo data-bar="gaz"/> or <br data-bar="gaz"/>.

A common convention for elements is x-foo; x-vendor-feature is recommended.

This handles most cases, since it's arguably rare that a developer would need all the power that comes with registering their elements. The syntax is also adequately valid and stable. A more detailed explanation is below.

Advanced Custom Elements and Attributes

As of 2014, there's a new, much-improved way to register custom elements and attributes. It won't work in older browsers such as IE 9 or Chrome/Firefox 20. But it allows you to use the standard HTMLElement interface, prevent collisions, use non-x-* and non-data-* names, and define custom behavior and syntax for the browser to respect. It requires a bit of fancy JavaScript, as detailed in the links below.

HTML5 Rocks - Defining New Elements in HTML
WebComponents.org - Introduction to Custom Elements
W3C - Web Components: Custom Elements

Regarding The Validity of The Basic Syntax

Using data-* for custom attribute names has been perfectly valid for some time, and even works with older versions of HTML.

W3C - HTML5: Extensibility

As for custom (unregistered) element names, the W3C strongly recommends against them, and considers them non-conforming. But browsers are required to support them, and x-* identifiers won't conflict with future HTML specs and x-vendor-feature identifiers won't conflict with other developers. A custom DTD can be used to work around any picky browsers.

Here are some relevant excerpts from the official docs:

"Applicable specifications MAY define new document content (e.g. a foobar element) [...]. If the syntax and semantics of a given conforming HTML5 document is unchanged by the use of applicable specification(s), then that document remains a conforming HTML5 document."

"User agents must treat elements and attributes that they do not understand as semantically neutral; leaving them in the DOM (for DOM processors), and styling them according to CSS (for CSS processors), but not inferring any meaning from them."

"User agents are not free to handle non-conformant documents as they please; the processing model described in this specification applies to implementations regardless of the conformity of the input documents."

"The HTMLUnknownElement interface must be used for HTML elements that are not defined by this specification."

W3C - HTML5: Conforming Documents
WhatWG - HTML Standard: DOM Elements

Lilia answered 24/1, 2016 at 3:59 Comment(0)
W
11

I would like to point out that the word "valid" can have two different meanings in this context, either of which is potentially, um, valid.

  1. Should an HTML document with custom tags be considered valid HTML5? The answer to this is clearly "no." The spec lists exactly what tags are valid in what contexts. This is why an HTML validator will not accept a document with custom tags, or with standard tags in the wrong places (like an "img" tag in the header).

  2. Will an HTML document with custom tags be parsed and rendered in a standard, clearly-defined way across browsers? Here, perhaps surprisingly, the answer is "yes." Even though the document would not technically be considered valid HTML5, the HTML5 spec does specify exactly what browsers are supposed to do when they see a custom tag: in short, the custom tag acts kind of like a <span> - it means nothing and does nothing by default, but it can be styled by HTML and accessed by javascript.

Wang answered 3/8, 2016 at 19:24 Comment(0)
B
7

To give an updated answer reflecting modern pages.

Custom tags are valid if either,

1) They contain a dash

<my-element>

2) They are embedded XML

<greeting xmlns="http://example.com/customNamespace">Hello!</greeting>

This assumes you are using the HTML5 doctype <!doctype html>

Considering these simple restrictions it now makes sense to do your best to keep your HTML markup valid (please stop closing tags like <img> and <hr>, it's silly and incorrect unless you use an XHTML doctype, which you probably have no need for).

Given that HTML5 clearly defines the parsing rules a compliant browser will be able to handle any tag that you throw at it even if it isn't strictly valid.

Backsaw answered 5/1, 2017 at 22:8 Comment(3)
Do you have a reference for this somewhere?Spoilage
Mostly agree, tho <img /> and <hr /> self-closing, rather than full XML closing, is still good practice and avoids a blank text node. It is sometimes even necessary in many tooling environments that use high-efficiency parsing validatorsPaoting
Some still put it as if it was a good thing, that HTML5 was defined such, that any use case which involves loading a document with an XML parser is doomed to fail. And what is the profit of preventing that use case? IMHO this was malicious and some XML hater wanted to make a point.Litt
L
5

Custom HTML elements are an emerging W3 standard I have been contributing to that enables you to declare and register custom elements with the parser, you can read the spec here: W3 Web Components Custom Elements spec. Additionally, Microsoft supports a library (written by former Mozilla devs), called X-Tag - it makes working with Web Components even easier.

Ludovika answered 15/10, 2012 at 18:20 Comment(11)
Portions are landing in Firefox and Chrome - we are working closely together and expect to have full implementations landed by the end of 2013.Ludovika
Now 2014, have full implementations landed?Meagher
But hang on, why would I want to declare them? Can't I just type them and they are defined on the fly?Panada
@JamieHutber and see your webpages break in the latest browsers one year from now. Rule #1 for browser interoperability: play by the rules.Darceldarcey
@MrLister A year?! :p no I completely redo websites every 6 monthsPanada
@HasibMahmud the specs are now finalized, and will land on Chrome Beta in a couple weeks, Firefox Aurora in ~6 weeks. You can use them in Firefox Aurora today by flipping the config flag dom.webcomponents.enabled to true.Ludovika
@MrLister As long as you follow the W3C recommendations for custom element and attribute names (x-* and data-*), you don't need to register them. It's been this way (and continues to be this way) for quite some time. Though this only lets you use them as generic DOM elements without any custom functionality. I've added an answer to help clarify this.Lilia
I've just updated the top-voted answer to reflect the latest changes to the spec(s) as of August 2016. Unfortunately, this answer is now completely obsolete. Thank you for your work on the standard!Pyrogen
@DanDascalescu I wouldn't say the answer is "completely obsolete", I linked to the living spec doc, which still reflects the current v1 final Custom Elements spec. The OP only asked if Custom Elements valid/standard - can you elaborate on why you said this?Ludovika
@DanDascalescu if you were the one who downvoted my answer - which still is an accurate reference to the spec that answers the simple question of the OP about whether Custom Elements were valid/standard - I would appreciate you not doing that.Ludovika
My apologies; I just don't see how this answer answers the OP's question, let alone any better than the top-voted answer. If it were my answer, I'd delete it.Pyrogen
L
3

Quoting from the Extensibility section of the HTML5 specification:

For markup-level features that can be limited to the XML serialization and need not be supported in the HTML serialization, vendors should use the namespace mechanism to define custom namespaces in which the non-standard elements and attributes are supported.

So if you're using the XML serialization of HTML5, its legal for you to do something like this:

<greeting xmlns="http://example.com/customNamespace">Hello!</greeting>

However, if you're using the HTML syntax you are much more limited in what you can do.

For markup-level features that are intended for use with the HTML syntax, extensions should be limited to new attributes of the form "x-vendor-feature" [...] New element names should not be created.

But those instructions are primarily directed at browser vendors, who would assumedly be providing visual styling and functionality for whatever custom elements they chose to create.

For an author, though, while it may be legal to embed a custom element in the page (at least in the XML serialization), you're not going to get anything more than a node in the DOM. If you want your custom element to actually do something, or be rendered in some special way, you should be looking at the Custom Elements specification.

For a more gentle primer on the subject, read the Web Components Introduction, which also includes information about the Shadow DOM and other related specifications. These specs are still working drafts at the moment - you can see the current status here - but they are being actively developed.

As an example, a simple definition for a greeting element might look something like this:

<element name="greeting">
  <template>
    <style scoped>
      span { color:gray; }
    </style>
    <span>Simon says:</span>
    <q><content/></q>
  </template>
</element>

This tells the browser to render the element content in quotes, and prefixed by the text "Simon says:" which is styled with the color gray. Typically a custom element definition like this would be stored in a separate html file that you would import with a link.

<link rel="import" href="greeting-definition.html" />

Although you can also include it inline if you want.

I've created a working demonstration of the above definition using the Polymer polyfill library which you can see here. Note that this is using an old version of the Polymer library - more recent versions work quite differently. However, with the spec still in development, this is not something I would recommend using in production code anyway.

Leisaleiser answered 16/7, 2013 at 21:53 Comment(0)
H
2

just use whatever you want without any dom declaration

<container>content here</container>

add your own style (display:block) and it will work with any modern browser

Helical answered 21/8, 2019 at 20:14 Comment(0)
P
1

data-* attributes are valid in HTML5 and even in HTML4 all web browsers used to respect them. Adding new tags is technically okay, but is not recommended just because:

  1. It may conflict with something added in the future, and
  2. Makes the HTML document invalid unless dynamically added via JavaScript.

I use custom tags only in places that Google does not care, for ecample in a game engine iframe, i made a <log> tag that contained <msg>, <error> and <warning> - but through JavaScript only. And it was fully valid, according to the validator. It even works in Internet explorer with its styling! ;]

Plausive answered 1/1, 2013 at 3:31 Comment(6)
It was valid to the validator because you were creating those elements with JavaScript, and the validator did not see them because it doesn't run your JavaScript. It would only see the page as it appears when first loaded.Christenson
Exactly. While not valid HTML, custom tags are still valid SGML and HTML is SGML after all. CSS can be used to style custom tags and it works perfect in IE. :) Also, you can specify your own DTD with your own custom elements in your DOCTYPE specification, so my custom tags may actually get validated even without JavaScript - but I don't care about them - a game engine GUI system is definetly not Google job :)Zouave
Well, there is a catch. You can't just throw in custom elements willy nilly. You do have to define and register them with the DTD in order for them to be consider "valid" HTML. Just because something works doesn't mean it's valid.Christenson
If you just add a qualifier to your element names, such as <x-msg>, <x-log>, etc. then you would be complying with the Web Components / Custom Elements spec.Gonophore
In a game engine where Webkit is only there to render your dynamic GUI, nobody will care about DTDs as well. Any unknown tag for HTML is HTMLUnknownElement for JS, still working perfectly with JQuery and CSS, so your GUI gets some semantics at the end: <inventory>, <item type="potion" sprite="2"> - so it's better to be called SGML + CSS rather than HTML, despite that HTML elements that have definition work as is - Buttons, lists, ...Zouave
The top answer explains which custom tags are valid HTML.Pyrogen
G
1

Custom tags are not valid in HTML5. But currently browsers are supporting to parse them and also you can use them using css. So if you want to use custom tags for current browsers then you can. But the support may be taken away once the browsers implement W3C standards strictly for parsing the HTML content.

Gay answered 17/7, 2013 at 13:3 Comment(1)
Maybe that'll happen when they stop supporting <center> and <marquee>?Cardsharp
S
1

I know this question is old, but I have been studying this subject and though some of the above statements are correct, they aren't the only way to create custom elements. For example:

<button id="find">click me</button>
<Query? ?attach="find" ?content="alert( find() );" ?prov="Hello there :D" >
I won't be displayed :D
</Query?>

<style type="text/css">

[\?content] {

display: none;

}

</style>

<script type="text/javascript">

S = document.getElementsByTagName("Query?")[0];

Q = S.getAttribute("?content");

A = document.getElementById( S.getAttribute("?attach") );

function find() {

  return S.getAttribute("?prov");

}

(function() {

A.setAttribute("onclick", Q);

})();

</script>

would work perfectly fine ( in newer versions of Google Chrome, IE, FireFox, and mobile Safari so far ). All you need is just an alpha character (a-z, A-Z) to start the tag, and then you can use any of the non alpha characters after. If in CSS, you must use the "\" (backslash) in order to find the element, such as would need Query\^ { ... } . But in JS, you just call it how you see it. I hope this helps out. See example here

-Mink CBOS

Sensitivity answered 3/11, 2014 at 19:19 Comment(1)
This is the oddest HTML I've seen lately :)Pyrogen

© 2022 - 2024 — McMap. All rights reserved.