htmltagscustomization

Is there a way to create your own html tag in HTML5?


I want to create something like

<menu>
    <lunch>
        <dish>aaa</dish>
        <dish>bbb</dish>
    </lunch>
    <dinner>
        <dish>ccc</dish>
    </dinner>
</menu>

Can it be done in HTML5?

I know I can do it with

<ul id="menu">
    <li>
        <ul id="lunch">
            <li class="dish">aaa</li>
            <li class="dish">bbb</li>
        </ul>
    </li>
    <li>
        <ul id="dinner">
            <li class="dish">ccc</li>
        </ul>
    </li>    
</ul>

but it is so much less readable. :(


Solution

  • You can use custom tags in browsers, although they won’t be HTML5 (see Are custom elements valid HTML5? and the HTML5 spec).

    Let's assume you want to use a custom tag element called <stack>. Here's what you should do...

    STEP 1

    Normalize its attributes in your CSS Stylesheet (think css reset) - Example:

     stack{display:block;margin:0;padding:0;border:0; ... }
    

    STEP 2

    To get it to work in old versions of Internet Explorer, you need to append this script to the head (Important if you need it to work in older versions of IE!):

     <!--[if lt IE 9]> 
     <script> document.createElement("stack"); </script>
     <![endif]-->
    

    Then you can use your custom tag freely.

    <stack>Overflow</stack>
    

    Feel free to set attributes as well...

    <stack id="st2" class="nice"> hello </stack>