HTML2DOM

September 14th, 2006. Tagged: (x)HTML(5), Ajax, JavaScript, News/personal, tools

Here's this HTML-2-DOM service - http://www.html2dom.com What it does is pretty simple - you paste some HTML code and the output is JS script code that uses DOM functions to produce the same result. Could be useful when you're working on an AJAX-style app that generates new content using JavaScript.

I build this simple script, inspired by this great book I was reading - "Build Your Own AJAX Web Applications". In the book, the author sometimes starts with writing up what is the HTML code for the result you want to achieve, and then goes ahead with giving the DOM code. Because, you know, DOM code can be quite verbose and sometimes a bit hard to follow. So I thought, why not write up a simple tool to automate this HTML to DOM transition.

The code is not complicated at all, it just takes the HTML, treats it as an XML document, then loops through all the elements of the XML doc and all the attributes for each element. The script is here, hopefully reusable and you can grab it for your own projects if you wish. You can check the source of html2dom.com's index page for an example how to use the html-2-dom class.

Some limitations of the script (that I know of) are result of the fact that I'm treating the HTML as XML document. So you might get some errors if the HTML you paste is not well-formed, with all closed tags and so on. Also you cannot use   and other entities, because XML doesn't know about them. What XML knows is only the pre-defined 5. And last, out of the different node types, my script understands only three - element, attribute and comment. I think it's enough for the practical purposes I was aiming at, even the comment type is a bit of a stretch.

So enjoy and as always, any feedback is welcome!

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov