CoderZone.org

Category: >> JavaScript >> Dynamically create HTML elements Bookmark and Share

<< lastnext >>

Snippet Name: Dynamically create HTML elements

Description: Dynamically create HTML elements with content wrapped inside them according to the DOM2 specifications.

Comment: (none)

Author: CoderZone
Language: JAVASCRIPT
Highlight Mode: JAVASCRIPT
Last Modified: December 01st, 2010

var Dom = {
  get: function(el) {
    if (typeof el === 'string') {
      return document.getElementById(el);
    } else {
      return el;
    }
  },
  add: function(el, dest) {
    var el = this.get(el);
    var dest = this.get(dest);
    dest.appendChild(el);
  },
  remove: function(el) {
    var el = this.get(el);
    el.parentNode.removeChild(el);
  }
};
var Event = {
  add: function() {
    if (window.addEventListener) {
      return function(el, type, fn) {
        Dom.get(el).addEventListener(type, fn, false);
      };
    } else if (window.attachEvent) {
      return function(el, type, fn) {
        var f = function() {
          fn.call(Dom.get(el), window.event);
        };
        Dom.get(el).attachEvent('on' + type, f);
      };
    }
  }()
};
Event.add(window, 'load', function() {
  var i = 0;
  Event.add('add-element', 'click', function() {
    var el = document.createElement('p');
    el.innerHTML = 'Remove This Element (' + ++i + ')';
    Dom.add(el, 'content');
    Event.add(el, 'click', function(e) {
      Dom.remove(this);
    });
  });
});
 
 
There haven't been any comments added for this snippet yet. You may add one if you like.  Add a comment 
© coderzone.org | users online: 7