i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Add and Remove Elements with JavaScript (reprise)

A long time ago (February 28th, 2005 to be exact), I wrote a post titled Add and Remove HTML elements dynamically with JavaScript. To this day, it continues to be the most highly traffic page on my website. However there is a number of things I'd like to point out that we can improve upon that implementation (since it is very outdated), and for the record, retract my three year old statement where I said "I hate JavaScript." That simply isn't true anymore, and it hasn't been true for a while now. Nevertheless, let's move onto business. Here's how you can simply add and remove HTML elements.

The basics

When it comes down right to it, the bottom line is this. You need three ingredients. Event attachment; the ability create and append elements, and the ability to remove them. For example:

attach event / add / remove

* element.addEventListener(el, type, fn);

* parent.appendChild(element);

* parent.removeChild(element);
Yeah. That's it. But this wouldn't be much of a post if there wasn't a demonstration of how to wrap this up in a easy to use interface. For this basic task, consider using two singleton's as a skeleton to act as your API which will appropriately wrap your Dom object, and an Event object.

Dom and Event

var Dom = {

  get: function(el) { },

  add: function(el, dest) { },

  remove: function(el)

};



Event = {

  add: function(el, type, fn) { }

};
Your implementation code can live in a closure wrapper when we add this behavior to the window's 'load' event.

implementation

Event.add(window, 'load', function() {

  // enclosed implementation here

});

Filling in the gaps

We can now essentially drop in our interface to do our heavy lifting.

Interface

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);

      };

    }

  }()

 };
Then simply use it to our convenience.

implementation

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);

    });

  });

});

You now have something that's easy as Pie! View the demonstration. Cheers and happy new year!

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.