Deleting dynamically generated elements

November 11th, 2009 Comments Off on Deleting dynamically generated elements

A coworker, Tommy, posed an interesting question to me the other day. How would one handle dynamically adding elements to a form, especially with regard to giving the user ability to remove those elements? We both admitted to implementing this a few times and he described to me his method of iterating through elements until the right node was found and then removing it.

As a habit I avoid DOM traversals whenever possible so I suggested an alternate solution. Instead of having a controller function look for some kind of unique ID or scan the DOM why not break down the control to the individual element and programmatically make the removing function a closure with a reference to each node. That way the code to remove an element is only ever concerned with its own instance. No crawling the DOM, no messy lookups, no muss no fuss.

If that didn’t make sense, perhaps this snippet will.

var addControls = function(element)
{
	var remove = document.createElement('input');
	remove.setAttribute('type', 'button');
	remove.setAttribute('value', '-');
	remove.onclick = function()
	{
		return function(self)
		{
			if(confirm('Are you sure?'))
				self.parentNode.removeChild(self);
		}(element);
	}
	
	element.appendChild(remove);
}

addControls(someNodeThatYouAlreadyFound);

Pretty simple. Questions? Let em rip in the comments.

Tagged , , ,

Comments are closed.