简体   繁体   中英

Can I define my own custom HTML Elements for use with css and js?

I've been reading all about these hot new custom HTML elements that you can make with today's browsers; It seems pretty interesting, to be honest. I've seen that the camp is out on this one, though; There's a lot of debate over whether to use them or not.

But that's not my question!

I've seen that in order to use custom HTML elements, you have to declare the element with javascript first; but I'm not finding this to be the case.

I simply ran an HTML document with the following code;

<div>
   <header-label>Text</header-label>
</div>

And it worked just fine in Chrome ( 40 ), FireFox ( 40 ), Internet Explorer 11, and Edge.

So I'm more confused than before; What is going on? Do I need to declare them, or not? Even CSS worked against it, as did jQuery selectors, angular directives; I couldn't find anything that led me to believe this was anything but a normal HTML element.

A) User-defined tags

You can use user-defined tags anywhere.

If you want to put <header-label> that's up to you. There are also custom HTML5 attributes which are things like

<input name="q" placeholder="Go to a Website">

or

<input type="email">

I investigated further and read those blog post comments and learned about...

B) HTML5 Custom Elements:

Per http://www.html5rocks.com/en/tutorials/webcomponents/customelements/

These let you do things like

<hangout-module>
  <hangout-chat from="Paul, Addy">
    <hangout-discussion>
      <hangout-message from="Paul" profile="profile.png"
          profile="118075919496626375791" datetime="2013-07-17T12:02">
        <p>Feelin' this Web Components thing.</p>
        <p>Heard of it?</p>
      </hangout-message>
    </hangout-discussion>
  </hangout-chat>
  <hangout-chat>...</hangout-chat>
</hangout-module>

These would otherwise be ignored (though the content and valid tags within them will still render without issue), however you can add these elements as valid DOM elements with:

var XFoo = document.registerElement('x-foo');
document.body.appendChild(new XFoo());

You can also base a user-defined element on an existing element to extend it, eg

var MegaButton = document.registerElement('mega-button', {
  prototype: Object.create(HTMLButtonElement.prototype),
  extends: 'button'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM