i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Add and Remove HTML elements dynamically with Javascript

UPDATE: There is a newer "up-to-date" version of this entry posted on January 02, 2008. View Add and Remove Elements with JavaScript (reprise).
I'm going to tell you straight up front. I hate Javascript. I hate it because it owns me. Today, it owned me. But within a few hours, I reversed the curse (In my past life I was a song writer). In the following article, I'm going to show you how you can dynamically create HTML elements with content wrapped within them according to the DOM2 specification. Why would this be useful? Just take one look at the add/remove HTML element demo. Those who have a GMail account probably recognize its similarity to the attachment feature when composing new email. Since Gmail's javascript seems to be hidden... or scrambled... or... whatever they did to it, I was left in the dark trying to figure this one out on my own. Read on to see some explanation of this garbagio that had me tearing my hair out. Lastly, just as a heads up, it may be better than you read the rest of this article using the Undesigned style sheet so that you may have better readability of the code.(Only available on old site design) First of all, the (x)html is real simple.

xHTML Snippet

<input type="hidden" value="0" id="theValue" />

<p><a href="javascript:;" onclick="addElement();">Add Some Elements</a></p>

<div id="myDiv"> </div>
The hidden input element simply gives you a chance to dynamically call a number you could start with. This, for instance could be set with PHP or ASP. The onclick event handler is used to call the function. Lastly, the div element is set and ready to receive some children appended unto itself (gosh that sounds wierd). Mkay, so far so easy. Now the JS functions.

addElement JavaScript Function

function addElement() {

  var ni = document.getElementById('myDiv');

  var numi = document.getElementById('theValue');

  var num = (document.getElementById('theValue').value -1)+ 2;

  numi.value = num;

  var newdiv = document.createElement('div');

  var divIdName = 'my'+num+'Div';

  newdiv.setAttribute('id',divIdName);

  newdiv.innerHTML = 'Element Number '+num+' has been added! <a href=\'#\' onclick=\'removeElement('+divIdName+')\'>Remove the div "'+divIdName+'"</a>';

  ni.appendChild(newdiv);

}

removeElement JavaScript Function

function removeElement(divNum) {

  var d = document.getElementById('myDiv');

  var olddiv = document.getElementById(divNum);

  d.removeChild(olddiv);

}
The addElement function sets a variable by grabbing the element of which we will append a child node to. So in this case, we use the classic getElementById method to track it down. We of course supply the empty 'myDiv'. The next three lines basically grab the value of the hidden input element and give your function a starting number to begin with. Then each time the function is called, your value is incremented. This is important for when you need to remove elements, since you'll need unique id's. You'll notice next the createElement is used to... well... make a new div element. But wait, it needs an id. Thus, we use the setAttribute method to append an id and a value to it. At this point, we have the uniquely named divIdName and we will plug that into the equation for our newdiv object. Now you're ready for some content garbagio to put inside your dynamic div element using the innerHTML property. And this is when it gets fun. Within your HTML supplied in the innerHTML of the dynamically created div element, you need to provide a link to remove itself. Afterall, that's the point of this whole thing, right? It wouldn't be flexible if all we could do is only add and not remove. So, a link is put inside with an event handler that calls the function removeElement. Great. Simple enough. Let's move onto that function. Okay, now that is easy. First off, it grabs the same parent div element by using getElementById and stores it in a variable. We then get the element to which we passed in as an argument to the function (which was created from the addEvent function), and we store that in another variable. Then voila! We remove like so: d.removeChild(olddiv);

Play with it, study it, tell your Uncle about it. This may not seem like a big deal, but it has potential to do some really cool stuff.

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.