Basic DOMTool Tutorial

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 :-).

The Input

The first that's needed is to decide what snippet of HTML you want to add to a document via javascript. For this example I will choose a very basic snippet that looks like this:

The Output

So if we put this into DOMTool and press "Create DOM Statements". The output is as follows:

In the process we are also warned that the compatibility function for creating named elements is required. This is because IE screws up adding name attributes into the DOM such that should you use setAttribute or the name property to set the name attribute, the name attribute is there but if you try and obtain that part of the DOM with innerHTML the name attribute is not seen.

So for full compatibility we need to use this function in our script and for the purposes of our example I will use this function. (To turn off this warning you can disable the compatibility mode in the options).

How to implement DOMTool's output

Ok, so DOMTool has given us it's output along with all of the nodes to append to the document, but how do you use this?

To make use of the output you need to create a function that runs the code generated by DOMTool. We also need to write a statement to append the top level element(s) to our chosen location. These are indicated by the "nodes to append" output.

So a very basic function would look like this: (Let's assume we want to add our form inside of a div with an id of "domtooltest")

Now let's put that together with a link to execute the insertion so that when we click the link the form is inserted.

View the example: DOMTool example.

Now if the "nodes to append" output displayed several elements like so:


We could just simply carry out an appendChild for each of them like so:

Thus appending each of them to our target element.

Show Comments