Why microformats is a good thing

I could have put the title “I have seen the Microformat Light” on this post, but I won’t. Neither am I suggesting that microformats replaces RDF (which some people have suggested they are trying to).

What I am suggesting, though, is that, given the the opportunity to mark up your human presentable content (read: HTML) with a well-defined microformat, you should. Mostly because writing microformat parsers is extremely easy.

Below is a 13-line hCalendar parser:

function parsehCalendar (doc){
    var evs = doc.getElementsByClassName("vevent");
    var ret = new Array();
    for (var i = 0,ev = evs[i];i++){
      var dtstart = ev.getElementsByClassName("dtstart").length?(ev.getElementsByClassName("dtstart")[0].title.toDate()):null;
      var dtend = ev.getElementsByClassName("dtend").length?(ev.getElementsByClassName("dtend")[0].title.toDate()):null;
      var title = ev.getElementsByClassName("summary").length?ev.getElementsByClassName("summary")[0].innerHTML:null;
      var location = ev.getElementsByClassName("location").length?ev.getElementsByClassName("location")[0]:null;
      var url = ev.getElementsByClassName("url").length?ev.getElementsByClassName("url")[0].href:null;
      ret[ret.length] = new Array(dtstart,dtend,title,location,url);
    }
    return ret;
}

document.getElementsByClassName is left as an exercise for the reader.

Comments

Comment from minghong on 2005-11-08 13:12

I think getElementsByClassName is not as simple as your 13-line parser. :-S

Comment from Anne van Kesteren on 2005-11-08 13:36

minghong, it is not that hard.

Comment from Arve on 2005-11-08 14:20

Oh, my document.getElementsByClassName function is only 21 lines of JS code, one line being a comment. If you don’t care about performance, or you don’t care about pre-XSLT browsers, the function can be written in 10 lines.

Comment from FataL on 2005-11-09 18:20

You can always use cssQuery instead of your own getElementsByClassName function.

Comment from neuro on 2005-11-10 20:18

Wow, cool thing, I love it!

Comment from Tantek Çelik on 2005-11-10 20:40

Well done Arve!

I’ve added this page to the hCalendar implementations section.

A couple of quick notes:

1. The parser should look for the class name “vevent” (not “hevent”):

var evs = doc.getElementsByClassName(“vevent”);

2. It would be good to add a line of code to get the description as well, since it is likely to show up due to its presence in the hCalendar creator.

Thanks!

Tantek

Comment from Arve on 2005-11-11 15:19

Tantek: Should be fixed now.

This discussion has been closed. No further comments may be added.