Javascript Gurus?

Consider the following code that I dug up off the internet, as I am not versed in JS:

    <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);
        remove: function(el) {
          var el = this.get(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() {
      , 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) {

As you can see, the code adds a specified element to the DOM. This works beautifully. The problem is that due to the way the removal is handled, clicking anywhere on the added element removes it. The element spans the entire screen. This is problematic, since I’m trying to use it to add form fields. Clicking on the field, of course, removes the element.

I need to break that “Dom.remove(this);” out and make it so that it removes the element if I click on an image or button associated with the element. Por ejemplo:


So if I click the X, it needs to remove its associated element. Clicking anywhere else should not affect the element.


I would recommend that you use jQuery or a similar js library. jQuery is designed to make DOM manipulation like this as simple as possible, and it really does make javascript much easier for those of us who aren’t programmers.

Anyway, if I understand your problem right, one way to handle it would be to start with the layout. Wrap the delete button and the form field in the same div element, e.g.:



When the user clicks on the image/button, you then delete the parent of the element That was clicked (the div wrapper), rather than the element itself. This will remove both the button and the field together, but do nothing at all unless the user clicks on the button. Given this HTML structure, something like this should work for the code you posted:


But really, investing a little time in learning jQuery will pay rich dividends…


To clarify, I do use jQuery in the majority of my projects. However this one, while large in scope, is small in stature. This will (hopefully) be the solitary instance of Javascript in the entire thing. I don’t really want to have to jack into jQuery for it.