domgen – Creating HTML with Javascript without DOM API

Tired of using Javascript DOM API for generating HTML dynamically? Meet domgen. domgen is a tool for easy dynamic content generation via Javascript. It generates DOM elements from dictionary specification similar to HTML and eliminates the need for cumbersome DOM Javascript API.

domgen uses a simple specification to generate the HTML. In some cases it’s more reliable to use DOM API to generate HTML instead of using innerHTML. We have had problems especially with iPhone when using innerHTML. See for example http://pastebin.com/LLk3J0iH or google “iPhone innerHTML” for more info. In fact, innerHTML is not even part of the HTML standard even though it exists on every browser.

So if you want to add dynamic HTML properly, you should use the Javascript DOM API. Consider the following short HTML where the contents inside body had to be generated:

<body>
    <div id="mydiv">my div</div>
</body>

Using Javascript DOM API:

// Get the body tag
var body = document.getElementsByTagName("body")[0];
// Create 'div' element
var mydiv = document.createElement("div");
mydiv.setAttribute("id", "mydiv");
mydiv.innerText = "my div";
// Attach the div to body
body.appendChild(mydiv);

And using domgen:

var spec = [
    'div',
    {
        id : 'mydiv',
        _innerText : 'my div'
    }
];
domgen.generate( domgen.get("body")[0], spec);
// or with jQuery
domgen.generate( $("body")[0], spec);

To me, domgen seems a lot easier to read and work with. Get code and more examples here: https://bitbucket.org/mfabrik/domgen

Leave a Reply

Your email address will not be published. Required fields are marked *