CoderZone.org

Category: >> JavaScript >> Dynamically add and remove elements Bookmark and Share

<< lastnext >>

Snippet Name: Dynamically add and remove elements

Description: Dynamically create HTML elements with content wrapped within them according to the DOM2 specification.

Also see:
» Add a hidden field to a form dynam...
» Add more fields to a form dynamica...
» Javascript Include - allows dynami...
» Remove empty lines from a string o...
» Add and Remove classes in Javascri...
» Remove empty lines from text files
» Read a web page directly in to a s...
» Get the URL of the referring page
» Allow access to a page only once
» Remove Duplicate Lines from a File
» Find All Elements By Class
» Dynamically create HTML elements
» Get Current Page URL
» Search array elements for a substr...
» Remove Extra Spaces From A String
» Dynamically Add/Remove rows in HTM...
» FLASHBACK: Syntax Elements
» Remove Duplicate Lines from a File
» Extract and Display all links on a...
» Easy page browser
» Create an HTML page on demand
» Page creation time #2
» Page creation time
» Remove all non-ASCII chars
» Find the current URL of the page
» Preview URL/Page On Hover
» Trippy Page
» Remove Duplicates
» Remove extra linebreaks

Comment: (none)

Author: CoderZone
Language: JAVASCRIPT
Highlight Mode: HTML4STRICT
Last Modified: May 28th, 2010

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Add and Remove Page Elements</title>
<style type="text/css">
#add-element {
  cursor: pointer;
}
</style>
 
<script type="text/javascript">
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);
    });
  });
});
 
</script>
</head>
 
<body>
 
<div id="doc">
  <p id="add-element">Click To Add An Element</p>
  <div id="content"></div>
</div>
 
</body>
</html>
 
 
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: 9