I understand that using custom html tags is improper for a variety of reasons, but I wanted to run a specific situation by you that might warrant a custom html tag and hopefully get told otherwise or possibly a better way of achieving my goal.

Throughout my code I have what I term as templates that are made up of a div tag with a template and a hidden class attached to it. This is not visible on the screen, but basically these "template" tags contains html that I use in Javascript to create a variety of different items. I do this so that I can style my templates in html rather than have to worry about mixing CSS in with my Javascript.

<!-- TEMPLATE -->
<div class="template hidden">
    <span>Random Container</span>
    <a href="#">Random Button</a>
</div>

In javascript I would do something like

var template = document.getElementById("template");
var clone = template.cloneNode(true);
clone.removeClass("template hidden");

I would rather be able to do something like this

<template class="hidden">
   <span>Random Container</span>
   <a href="#">Random Button</a> 
</template>

So that if I have multiple templates in a single div I can grab them all rather than having to give them unique class names. Of course my reasoning for needing an implementation goes a lot deeper than this, but its not necessary to waste your time with the details. Let's just say that it will help clean up my Javascript ALOT.

Because the custom template tag is hidden and really is nothing more than a container that is convenient to call within javascript with document.getElementsByTagName("template"); Is this ok to do? I would probably prefix the tag with a custom name in case template ever gets implemented into html.

有帮助吗?

解决方案

Why not use one of HTML5's data attributes? They are for storing private data or custom info.

For your case, you could add data-type="template" or data-name="template" and then search and remove based on that. One simple function just like you would write to remove your <template> tag, but without breaking rules.

So, using your example, <div data-type="template" class="hidden"></div>

其他提示

Modern browsers generally “support” custom tags in the sense of parsing them and constructing DOM nodes, so that the elements can be styled and processed in scripting.

The main problem is IE prior to IE 9, but it can be handled using document.createElement('...') once for each custom tag name.

Another problem is that validators will report the tags as errors, and if there are loads of such errors, you might not notice some real errors in markup. In principle you can create your own DTD to deal with this (I have an HTML DTD generator under construction, but it is trickier than I expected...).

With these reservations, use custom tags if they essentially simplify your job as compared with using classes.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top