»
EnglishFrenchVietnamese

Print - JavaScript Add-Remove HTML Elements with DOM - JavaScriptBank.com

Full version: jsB@nk » Snippet » JavaScript Add-Remove HTML Elements with DOM
URL: https://www.javascriptbank.com/javascript-add-remove-html-elements-with-dom.html

JavaScript Add-Remove HTML Elements with DOM © JavaScriptBank.comThis JavaScript code example will dynamically add/remove HTML elements with content included within them according to the DOM2 specification. A very easy JavaScript code to learn and use DOM.Try more JavaScript codes on jsB@nk to handle DOM better: - JavaScript OOP with Input Display Toggle - JavaScript Content Auto-Indexing using DOM - JavaScript Add More Unlimited Input Fields

Full version: jsB@nk » Snippet » JavaScript Add-Remove HTML Elements with DOM
URL: https://www.javascriptbank.com/javascript-add-remove-html-elements-with-dom.html



JavaScript
<script type="text/javascript">// Created by: Dustin Diaz | http://www.dustindiaz.com/// This script downloaded from www.JavaScriptBank.comvar 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>


HTML
<div id="doc">  <p id="add-element">Add Elements</p>  <div id="content"></div></div>