Attributes on custom HTML elements

When working with custom HTML elements in web components, should I still name custom attributes with the prefix data ?

For example:

<!-- Should form be data-form? -->
<my-button form="foo">click me</my-button>

In general, there is no difference between custom elements and predefined. You might create an element of your choice with document.createElement and register it with document.registerElement . The result would be:

console.log(document.createElement('my-button').constructor);
//⇒ function HTMLElement() { [native code] }
console.log(document.registerElement('my-button'));
//⇒ function my-button() { [native code] }
console.log(document.createElement('my-button').constructor);
//⇒ function my-button() { [native code] }

As you could see, once registered, the element is awarded with it's own constructor. That provides an ability for components to behave in it's own way. But:

console.log(document.createElement('my-button').__proto__.__proto__);
//⇒ HTMLElement

is still a good old plain HTMLElement . So, the rules for attribute naming were not changed.

Please note, that libraries, like polymer, might add additional attribute handling; the above is true for plain web-components only.


No, that's not necessary.

Existing HTML elements have a defined set of attributes, which means you would invalidate the HTML by just adding any attribute. By introducing the data- attributes, it was made possible to extend existing elements without invalidating them.

Web components are custom elements. They have no defined set of attributes, you define them yourself. Whether or not you use data- attributes is completely up to you, but you don't have to. Your component cannot become invalid because there is no definition of valid for it.

If you care about semantic/valid HTML, this answer may be relevant to you too: Are custom elements valid HTML5?. In short: use a dash in your component name to make sure it's picked up as valid HTML.

链接地址: http://www.djcxy.com/p/24958.html

上一篇: ggplot2:合并geom的图例

下一篇: 自定义HTML元素的属性