DOM Builder

Build elements quickly

HTML

<button id="demo">Create new element</button>
<div id="container"></div>

CSS

.some-class{
    color:#fff;
}

JavaScript

var count = 1;

function demo(){
    
    var new_div = Builder.create('div', function(el){
        
        //attributes
        this.class = 'some-class';
        this.id = 'some-div-' + count;
        
        //manual stuff
        el.style.backgroundColor = 'blue';
        
        //append a child
        this.create('span', function(){
            var reset_name = 'Test ' + count;
            
            //append text node
            var name = this.text(reset_name);
            
            //append input
            var input = this.create('input', function(){
                this.type = 'text';
                this.placeholder = 'some text';
                
                this.on('keyup', function(e){
                   name.nodeValue = this.value; 
                });
            });
            
            //append a button
            this.create('button', function(){
                this.text('alert input');
                
                //events
                this.on('click', function(){
                    alert(input.value);
                });
            });
            
            //append another button
            this.create('button', function(){
                this.text('reset name');
                
                //events
                this.on('click', function(){
                    name.nodeValue = reset_name;  
                });
            });
            
        });
        
        // inject raw html
        //this.html('<hr>');
        
        //do jquery stuff
        //$(el).hover(...
    });
    
    //append the new element                             
    this.parentNode.appendChild(new_div);
    count++;
}

document.getElementById('demo').onclick = demo;

/**
 *    DOM Builder - provides an easy way to dynamically create elements
 */
var Builder = function(el){
    //set root and element shortcuts
    this.root = el;
    
    //create a new element
    this.create = function(tag, func){
        var...