Search code examples
htmltags

How to create custom tags for HTML


How can I create custom meta tags for HTML, with special attributes and behavior?


Solution

  • There's an interesting and in depth article from HTML5Rocks.com on how to work with custom elements : Custom Elements: Defining New Elements in HTML

    Here's an excerpt from the article on how to do it.

    Instantiating elements

    The common techniques of creating elements still apply to custom elements. As with any standard element, they can be declared in HTML or created in DOM using JavaScript. Instantiating custom tags

    Declare them:

    <x-foo></x-foo>
    

    Create DOM in JS:

    var xFoo = document.createElement('x-foo');
    xFoo.addEventListener('click', function(e) {
        alert('Thanks!');
    });
    

    Use the new operator:

    var xFoo = new XFoo();
    document.body.appendChild(xFoo);