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);
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>
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:
[[FORM ELEMENT]] [X]
So if I click the X, it needs to remove its associated element. Clicking anywhere else should not affect the element.
Thoughts?