Tuesday, October 16, 2012

building custom tags in html5 and javascript, part 1

If you've had the chance to work with Facebook's Social Plugins, you've likely come across the option to embed their widgets using XFBML. They offer a similar "HTML5 compatible" option, but I tend to think the custom, name-spaced tags option is neat. So, let's explore one way to do that.

As an example of the usefulness, I'll use my recently completed book of small potatoes (wisdom of the ancients) from thepointless.com. With each wise guy quote, we see markup in the following format, which renders a voting widget, with the help of some fancy JavaScript:

<tpdc:voter method='/ajax/pointlisting_vote' record_id='37' vote='1'

(Rather the post the full script that does the magic here, I'll be using some trivial simplified JavaScript here for conciseness. You can take a peek at it in action if you're interested.)

To prevent Internet Explorers 7 and 8 from giving us the silent treatment come script-time, our custom tags need to live in a namespace. (Other browsers, as far as I know, ignore the namespace altogether.) And the namespace must be defined in the opening html tag:

<html xmlns:tpdc="http://www.thepointless.com/ns/tpdc">

Now, as you might imagine, a little JavaScript magic is needed to work with these nodes gracefully. And although a touch hacking, it may not be as hackish as you'd expect! As seen on the thepointless.com, here is the function we use to grab these nodes and "import" their attributes correctly:

var getNodes = function(n, q) {
    try {
        // i think "r" stands for "return" here.

        // in any event, our first step is to try to find the nodes
        // by their full names -- that is, with the namespace.
        var r = n['getElementsByTagName'](q);
        if (r.length < 1) {

            // ... and if we don't find anything, omit the namespace,
            // if present.
            var p = q.split(":");
            if (p.length == 2) {
                r = n['getElementsByTagName'](p[1]);

        // import attributes, for each node
        for (var i = 0; i < r.length; i++) {

            // for each attribute in r[i]

            // first, make sure we're not attempting to RE-import attributes.
            var ri = r[i];

            if (!ri.__attributes_imported) {

                // so, we basically iterate through each attribute and
                // "re-attach" it to the node directly. seems silly, but
                // it allows our scripts to operate on these attributes
                // later much more naturally.
                for (var ai = 0; ai < ri.attributes.length; ai++) {
                    var att = ri.attributes[ai];
                    if (!ri[att.name]) {
                        ri[att.name] = att.value;
                ri.__attributes_imported = true;

        // and finally, give that list of nodes back.
        return r;
    } catch (e) {
        return [];
} // getNodes()

This getNodes() implementation works in recent versions of Chrome, Firefox, Safari, and IE7+ (not tested in IE6). One-off use of the function works similarly to (but not exactly like) the normal getElementByTagName() function. So, if we want to work with all the tpdc:voter nodes, we could do this:

// get an array of tpdc:voter nodes.
var voterNodes = getNodes(document, "tpcd:voter");

// for each one, let's add an onclick event that simply displays
// the method attribute.
for (var i = 0; i < voterNodes.length; i++) {

  // to be clear, the "this" here is the node itself
  voterNodes[i].onclick = function() { alert(this.method); }

Pretty simple. And working with child nodes is just as easy. Suppose we want to loop through all the tpdc:voter nodes and make each tpdc:count node with a value of 10 or more bold. Now, with this trivial example, we could do this globally, like so:

// get all the tpdc:count nodes.
var countNodes = getNodes(document, "tpdc:count");

// make each one with an innerHTML value >= 10 bold
for (var i = 0; i < countNodes.length; i++) {
  if (parseInt(countNodes[i].innerHTML) >= 10) {
    countNodes[i].style.fontWeight = 'bold';

Or, we can work within the context of a single tpdc:voter node, as we might in a voter node's class method. A trivial example again, but this works as expected:

// assume we already have a tpdc:voter node, voterNode
var countChildren = getNodes(voterNode, 'tpdc:count');
// act on all tpdc:count nodes found.
for (var ci = 0; ci < countChildren.length; ci++) {
  if (parseInt(countChildren[ci].innerHTML) >= 10) {
    countChildren[ci].style.fontWeight = 'bold';


But, we're not done yet. What we really want is the ability to treat these custom tags like instances of a real class. And we can! We can define a namespace (empty object) with some classes (functions) and bind them semi-automagically to the DOM nodes.

Let's consider a TPDC namespace with two very simple classes:

// the namespace
var TPDC = {};

// class Simple
TPDC.Simple = function() {
  // we can do things at object "instantiation" time
  this.innerHTML = "Simple";
} // class TPDC.Simple()

// class LessSimple
TPDC.LessSimple = function() {

  // we can also define object methods
  this.makeSimple = function() {
    this.innerHTML = "Simple";
  } // TPDC.LessSimple.makeSimple()

  this.onClick = function() {
  } // TPDC.LessSimple.onClick()

  this.innerHTML = "Less Simple";
} // class TPDC.LessSimple()

Simple. And so is binding our whole TPDC "namespace" to the appropriate document nodes:

for (var k in TPDC) {
  var tpdc_nodes = getNodes(document, 'tpdc:' + k);
  for (var i = 0; i < tpdc_nodes.length; i++) {

And, if we want to stuff our getNodes() function stuffed neatly away in a shared library, we can also add a convenient little binder method:

var BindNS = function(ns_name, parent) {
  // "find" the namespace within its parent, given its name
  var p = parent || this;
  var ns = p[ns_name];

  // apply the class constructors to the document nodes
  for (var k in ns) {
    var ns_nodes = getNodes(document, ns_name.toLowerCase() + ":" + k.toLowerCase());
    for (var i = 0; i < ns_nodes.length; i++) {
} // BindNS()

And then bind our simple TPDC class with one line:


And at this point, any tags in our document that look like these will operate as though they're instances of our Simple and LessSimple classes:


They also operate as generic DOM nodes too, of course. Your JavaScript classes are, in many respects, subclasses of the Node class.

Two things to remember though:

1. Most browsers ignore the namespace. So, this approach doesn't grant you an ability, so far as I know, to create namespaces with identical class names. You can work around this by including the namespace again as a prefix in your class names if you need to.


2. It's invalid markup! It's served up with a text/html content type and an HTML5 doctype, which explicitly forbids tag namespaces. So, you might even call it grossly invalid! That said, of all the custom tag variations I tested, this syntax actually provided the most consistent behavior.

In any event, I like the way this works. I can simplify and minimize both my markup and my script using this approach. And I definitely plan on playing with it more. One thing I'm pondering is an elegant way to automagically attach custom child tags to custom-tag parents in a helpful and meaningful way.

So, if anyone has any thoughts on that (or any of this), I'd be interested in your feedback.

And of course, I encourage you to check out the working examples of this concept at thepointless.com, starting with the book of small potatoes!


UPDATE: There's now a building custom tags in html5 and javascript, part 2!


  1. This is an awesome post. Really very informative and creative contents. This concept is a good way to enhance knowledge. I like it and help me to development very well. Thank you for this brief explanation and very nice information. Well, got good knowledge.
    WordPress development company in Chennai

  2. become a new player in the casino good top online casinos I understood, I understood that on this site, luck will smile at me

  3. Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too..
    Oracle DBA Online Training

  4. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    msbi online training

  5. Resources like the one you mentioned here will be very useful to me ! I will post a link to this page on my blog. I am sure my visitors will find that very useful

    Tableau online training

  6. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
    msbi online training

  7. Thanks for such a great article here. I was searching for something like this for quite a long time and at last I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays.
    Sql server dba online training

  8. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me.

    ReactJS Online Training

  9. Thanks for sharing Great info… learning driving from experienced instructors help you to learn driving very fast. Driving School Melbourne


  10. When you feel any kind of body pain, it is best if you go to the doctor for treating it. Sometimes body pain can be the symptom of some serious disease. Sometimes body pain attacks us suddenly because of which you may not able to get the help of the doctor. In those situations, to get quick and effective pain relief, you can take the help of painkillers though they cannot cure your pain. As your painkiller, choose Tramadol 50 mg which is very effective. This painkiller is available in the market with the name of Ultram. To use this painkiller, you can get it easily. Buy Tramadol online and get this painkiller at an affordable price.
    Buy Tramadol online

  11. Howdy! I could have sworn I’ve been to this blog before but after looking at many of the posts I realized it’s new to me. Regardless, I’m certainly delighted I discovered it and I’ll be book-marking it and checking back often!
    Tech geek

  12. live draw hk banyak terdapat perbedaan dari situs2 penyedia live hk ini. Sedikit saran apabila anda setiap harinya mengikuti live draw hk kami pastikan selalu menggunakan situs live hk yang kami rekomendasikan saja. Termasuk juga untuk live draw sgp ataupun live sgp alternatif ini.

  13. Thanks for sharing such a great information. Its really nice and informative sql training
    and ms sql server tutorial.

  14. Poker online situs terbaik yang kini dapat dimainkan seperti Bandar Poker yang menyediakan beberapa situs lainnya seperti , kemudian,, dan yang paling akhir yaitu Jangan lupa mendaftar di panenqq


  15. This post is really nice and informative. The explanation given is really comprehensive and informative. I want to share some information about the best oracle dba training and weblogic server tutorial training videos. Thank you .Hoping more articles from you.

  16. After I initially commented I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on each time a comment is added information I receive 4 emails with the same comment. There has to be a means you can remove me from that service? Thanks a lot!

  17. This web site truly has all the information and facts I needed concerning this web site subject and didn’t know who to ask.

  18. Great technology web site you have got here.. It’s hard to find quality writing like yours these days. I really appreciate individuals like you! Take care!!

  19. Good article! I found some useful educational information in your blog about React Js, it was awesome to read, Java training in chennai thanks for sharing this great content to my vision
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

  20. This creative article has widened my knowledge . The brief explanation of this blog helps me to move further to the next level in this subject matter. Thanks for sharing this blog. Web Designing Course Training in Chennai | Web Designing Course Training in annanagar | Web Designing Course Training in omr | Web Designing Course Training in porur | Web Designing Course Training in tambaram | Web Designing Course Training in velachery

  21. Paid marketing can be an excellent way to increase your visibility and conversion rates. Resurge Pills