Muffinresearch Labs by Stuart Colville

DOMTool | Comments (33)

Posted in Code on 28th November 2006, 6:40 pm by Stuart

I’ve had this idea kicking around for a while that it would be useful to build some kind of utility that took HTML as an input and output the correct DOM methods for inserting that content into a document. To start with I thought this would be some kind of PHP regex extravaganza, but in talking to Mike Davies and kicking some ideas around about this, I realised that the best way to make this work would be to use innerHTML to insert the HTML and to then recurse down the inserted HTML to generate the DOM insert statements. There’s a beautiful kind of irony in using innerHTML to indirectly generate DOM structures. Also the forgiving nature of innerHTML will mean that you can get away with missing closing tags etc.

Who is this Tool for?

It’s for either programmers who want to save time not having to write out long DOM structures manually (you can read that as lazy programmers if you want!). Plus it’s also potentially a useful starting point for someone who is not knowledgeable of JavaScript but would like to experiment with inserting HTML into a Document using DOM methods.

When writing this tool I had in mind making it possible to prototype code quickly by taking a snippet from an HTML mock. Obviously for production use the output of this tool would probably need optimising in most cases.

How do I use it?

To use DOMTool simply paste an HTML snippet into the input field, press “Create DOM Statements” and voila, there you have the DOM sequence to create that content.

To make it easier when you have multiple children to append to your target element, I have provided the list of top level elements you need to append in the “Nodes to append” output.

For example if my snippet looks like this:

<p>test1</p>
<p>test2</p>
<p>test3</p>

The generated DOM sequence is:

var p1=document.createElement('P');
var txt1=document.createTextNode('test1');
p1.appendChild(txt1);
var p2=document.createElement('P');
var txt1=document.createTextNode('test2');
p2.appendChild(txt1);
var p3=document.createElement('P');
var txt1=document.createTextNode('test3');
p3.appendChild(txt1);

To use this you will have to append each paragraph into your chosen target like so:

var t = document.getElementById('target');
t.appendChild(p1);
t.appendChild(p2);
t.appendChild(p3);

As this code is generated in such a way that you are building up the DOM structure and then appending it, I’ve stuck to using setAttribute as this shouldn’t cause any issues. Let me know if you come across and special cases where cross-browser workarounds are required in the generated code and I’ll implement them.

29-11-06: Name attribute Compatibility function. I’ve added a basic compat function to handle the problem with name attributes in IE so this function would need to be included in the script that makes use of the output should you be trying to create any elements with name attributes. The function is only displayed when name attributes are detected so if it’s not there you don’t need to worry about it.

30-11-06: Fixed style attributes to be set using properly camel-cased styles. Also I’ve addressed classes as although they were being set using setAttribute (According to IE’s DOM inspector applying CSS rules didn’t work. I have therefore changed them to be set using the className property instead.

Lastly but not least thanks to Mike Davies for being such an excellent sounding board, for contributing his ideas and for carrying out some pretty extensive testing.

Try it out

You can test DOMTool for yourself here: DOMTool V1.1. Be sure to let me know if you have any suggestions for improvements etc.

Caveats

The output varies slightly depending on which browser you use to generate the content. IE seems to gag on attributes which I should be able to fix in due course, but for now I would recommend using Firefox for generation but similarly any modern browser should do a reasonable job of it.

Also in testing Mike found that IE doesn’t like generating script elements for inline code, but it’s very unlikely that doing this is a good idea in any case.

This is very much a beta development (read that as buggy if you want!) so if you have ideas on optimisations or improvement please impart your wisdom in the comments below.

Changelog

1.1
5-12-06: Added warnings for bad practices + options to disable warnings and the IE compat mode. Provided fix to quotes for in-line events. Added hasAttribute wrapper for IE so DOMTool now works in IE. Will need to look at fixing/filtering certain strange attributes that are generated by Opera and IE’s inner HTML. This version is also localisable, so if anyone wants to create a localised version of DOMTool please get in touch.
1.03
5-12-06: Added suppport for inline events
1.02
30-11-06: Fixed style attributes and className to use properties so that they work as expected in IE.
1.01
29-11-06: Added compat function for IE6’s lack of ability to handle name attributes correctly
1.0
29-11-06: Original Release

Post Tools

Comments: Add yours

1. On November 28th, 2006 at 11:13 pm Anonymous said:

Nice work, but…

The first thing I tried was creating an input tag with a name attribute. IE6 will not allow you to create named elements using setAttribute, so the generated code would not have worked (or rather, an input tag would have been created, but without a name attribute in IE6).

Just FYI.

2. On November 29th, 2006 at 1:09 am Bramus! said:

Very nice! Tested it with some nested elements having classed and ids and such; and found it working like a charm :)

3. On November 29th, 2006 at 1:39 am Keith Bell said:

Now that’s handy!

I’ve used Dan Webb’s DOMBuilder reliably to insert big chunks of HTML into a page. The syntax is pretty simple, but it still takes longer that just writing out HTML, so DOMTool could be a real time-saver for many folks.

4. On November 29th, 2006 at 2:04 am Stuart Colville said:

@Anonymous: You’re absolutely right. I’ve added a compat function that the user will need to use when creating elements with name attributes so that the name attribute will be correctly created in IE6.

5. On November 29th, 2006 at 9:22 am zproxy said:

This is a great concept.

What about combining it with the html designer?

I think i will research sometime later this aspect for the jsc project of mine:)

This could be a refactoring addin — select text and convert to dom calls. yeah, similar to current paste xml and converty to XLinq :)

cheers

6. On November 29th, 2006 at 11:02 am Matthew Pennell said:

That’s how jQuery does it (by creating innerHTML and iterating through it).

7. On November 29th, 2006 at 11:44 am Stuart Colville said:

@Matthew: Does jQuery do that dynamically? The point here is that you don’t add additional overhead into your scripts by using a wrapper to DOM methods, instead the overhead is upfront giving you the ability to optimise and tweak as you see fit.

8. On November 30th, 2006 at 4:24 pm Ajaxian » DOMTool: Given HTML generate DOM methods said:

[...] Stuart Colville has developed a tool for generating DOM methods from an HTML snippet called DOMTool: The idea is that you drop a snippet of HTML in the input and the tool puts it into the document with innerHTML and then loops through that structure to generate the DOM methods needed to append that piece of HTML into a document from a script. There’s a kind of beautiful irony in using innerHTML to generate DOM methods. [...]

9. On November 30th, 2006 at 10:08 pm Leonya said:

Very nice indeed, but it could be much more useful if actual properties were used, instead of using setAttribute for everything. I mean, instead of this:

div1.setAttribute(’id’,'user’);

it would be great to have this:

div1.id = ‘user’;

Or:

div1.style.display = ‘none’;

instead of

div1.setAttribute(’style’,'display: none’);

10. On December 1st, 2006 at 1:18 am Stuart Colville said:

@Leonya: Thank-you for your comment. I agree that setAttribute for style is not that useful when it comes to IE, however I would note that setting inline styles is really a bad practice that should be avoided in most cases. However that aside for completeness I have fixed style attributes so they are set using style properties with camel-case conversions for hyphenated styles.

I can’t see what’s wrong with setting ids with setAttribute so if you have a specific reason why this is a bad thing please let me know.

11. On December 1st, 2006 at 2:43 pm Nick Fitzsimons said:

IE6 is giving me an error at line 88, due to the evaluation of

elc[i].hasAttribute("name")

as IE doesn’t support the DOM 2 Core method “hasAttribute”.

12. On December 1st, 2006 at 3:40 pm Stuart Colville said:

@Nick: That’s exactly why I don’t recommend running DOMTool itself in IE (See the heading “Caveats”).

The output should however be compatible with IE6+ so if you find any problems with running the outputted code in IE please let me know.

13. On December 4th, 2006 at 12:08 pm Infected-FX » Enlaces rápidos XV said:

[...] DOMTool Si deseas ahorrar tiempo y no escribir esas largas estructuras de DOM esta herramienta te facilitará la vida. [...]

14. On December 4th, 2006 at 2:01 pm jummie jummie » DOMTool said:

[...] DOMTool. Ein nützliches Tool, welches HTML-Code nimmt und die entsprechenden DOM-Methoden ausgibt um diesen Code zu erzeugen und in ein Dokument einzufügen. Aussehen tut das folgendermaßen: [...]

15. On December 5th, 2006 at 3:32 pm mie said:

I’m totally surprised with this tool. It’s brilliant. For a beginner in JS like me, this tool is very useful. I wish there is a short documentation for beginner like me to understand where & what possible to do when the output generated.

16. On December 5th, 2006 at 3:37 pm Stuart Colville said:

@mie: Thanks a lot for your comment. I am close to releasing a new version with quite a few extra features/fixes as well as some proper documentation and tutorials so stay tuned.

17. On December 5th, 2006 at 6:45 pm Stoyan said:

Good job. I like how the generated vars have the names of the elements they create.

You might be curious to see my solution to the same problem – dom2html. I’m taking a different approach – taking the HTML and trying to produce an XML document out of it. Then navigating this XML doc with DOM methods. Hope you’ll like it :)

18. On December 14th, 2006 at 1:23 am Basic DOMTool Tutorial said:

[...] I’ve had some brilliant feedback on DOMTool and several people have emailed me asking for a basic tutorial on how to use the output. So if you’re familiar with using the DOM to add content to a page then this probably won’t be terribly exciting and you can carry on reading the next post in your feedreader . [...]

19. On December 19th, 2006 at 6:27 pm SSDD Web Design » Article » Online Tool for Creating DOM Statements said:

[...] DOMTool: “To use DOMTool simply paste an HTML snippet into the input field, press ‘Create DOM Statements’ and voila, there you have the DOM sequence to create that content.” [...]

20. On January 8th, 2007 at 6:53 pm DOMTool: Given HTML generate DOM methods said:

[...] Stuart Colville has developed a tool for generating DOM methods from an HTML snippet called DOMTool: The idea is that you drop a snippet of HTML in the input and the tool puts it into the document with innerHTML and then loops through that structure to generate the DOM methods needed to append that piece of HTML into a document from a script. There’s a kind of beautiful irony in using innerHTML to generate DOM methods. [...]

21. On March 8th, 2007 at 3:33 pm Best of February 2007 | Smashing Magazine said:

[...] DOMTool To use DOMTool simply paste an HTML snippet into the input field, press “Create DOM Statements†and voila, there you have the DOM sequence to create that content. [...]

22. On March 9th, 2007 at 2:15 am Happy Life » Web-Sites of the Month: Best of February 2007 (zz from Smashing Magazine) said:

[...] DOMTool To use DOMTool simply paste an HTML snippet into the input field, press “Create DOM Statements†and voila, there you have the DOM sequence to create that content. [...]

23. On March 16th, 2007 at 4:58 am 煎蛋 » 网络最佳之2007å¹´2æœˆå· said:

[...] 快速高亮效果 Weebly – 傻瓜å¼å»ºç«™ DOMTool:HTML æºç å·¥å…· WriteMaps:站点地图工具 Spotplex:blog 峿—¶è¯„测 WordPress Feed [...]

24. On April 13th, 2007 at 1:03 am wendelmaques » ModalBox 1.5 said:

[...] domtool pode ser usada para receber conteúdo HTML e criar uma estrutura DOM. [...]

25. On May 7th, 2007 at 7:04 am Rajesh said:

Is there a packaged version of this tool that can be used within an application on-the-fly for converting HTML blocks into DOM statements? Something like …

var theHTML = “[p][strong]this is a test[/strong][/p]“;
var theDOM = DOMTool(theHTML);
eval(theDOM);

Or maybe just…

DOMTool(theHTML);

which could automatically call eval() at the end. How about that?

26. On May 15th, 2008 at 1:31 am 20 Useful Tools to Make Web Development More Efficient | Six Revisions said:

[...] 9. DOMTool [...]

27. On May 17th, 2008 at 8:36 am Craig said:

I developed a JS function called BetterInnerHTML that does just that – you pass an HTML string, like you would with innerHTML, but it uses DOM node creation methods to create the content. It’s therefore as easy to use as innerHTML but doesn’t have the problems.

It’s just 1Kb of code and available here:
http://www.optimalworks.net/resources/betterinnerhtml/

more details here:
http://www.optimalworks.net/blog/2007/web-development/javascript/innerhtml-alternative

28. On May 17th, 2008 at 9:27 am Stuart Colville said:

@Craig: looks exactly what Rajesh is looking for, nice work.

@Rajesh: Yes there’s several utilities as part of framworks that are designed to do just that. However, the point of DOMTool was to provide a way to output the specific lines of code (albeit unoptimised) so that you the developer has full control over your code rather than handing off to a wrapper function to do it for you. Also parsing structures on the fly to then inject them using DOM methods will be slower due to the extra step involved. Again this is why offline conversion made sense.

29. On May 29th, 2008 at 1:57 am 20个让你web开呿›´å…·æ•ˆçŽ‡çš„å·¥å…·(上) - è¸ç ´’BLOG said:

[...] 9. DOMTool [...]

30. On June 30th, 2008 at 8:58 am 20个有用的工具让你的web开呿›´æœ‰æ•ˆçŽ‡ï¼ˆ1) | è€é»‘专用 said:

[...] 9. DOMTool [...]

31. On July 25th, 2008 at 3:29 pm Seo Peru :: Recursos para Webmaster said:

[...] DOMTool DOMTool fue creado para reducir el tiempo que tarda el código en estructuras DOM. DOM tiene opciones tan [...]

32. On December 9th, 2008 at 4:52 am Luis Alarcón, Blog » Blog Archive » 21 herramientas útiles para un desarrollo web más eficiente said:

[...] DOMTool fue creado para reducir el tiempo que tarda el código en estructuras DOM. DOM tiene opciones tan simples como copiar su código HTML en el DOMTool y a continuación, hacer clic en un botón. [...]

33. On October 3rd, 2009 at 3:26 am 20 Useful Tools to Make Web Development More Efficient | 9Tricks.Com - Tips - Tricks - Tutorials said:

[...] 9. DOMTool [...]







XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Using Loggerhead with mod_wsgi|(0)

Here’s a post I wrote over on the Project Fondue Blog about our use of Loggerhead with mod_wsgi under Apache. Loggerhead is the rather nice branch viewer for bazaar branches as used on Launchpad.net.

If you’re not already subscribed to the Project Fondue blog feed then I can recommend it, as there should be some interesting posts coming out of there in the coming months (yes I’m unashamedly biased!).

Ubuntu: Turn off changing workspace with mouse wheel|(1)

I found the changing with the workspace with the mouse wheel really annoying. To disable it go to System => Preferences => CompizConfig (available if the compizconfig-settings-manager package is installed) and uncheck “Viewport Switcher” which is under the “Desktop” heading.

Photos on Flickr

© Copyright 2004-10 Stuart Colville, all rights reserved. May contain traces of Muffin. Powered by WordPress. Hosting by Slicehost.com This page was baked in 0.776s.