Dynamically Add and Remove Text Box Elements

This script makes use of the createElement, appendChild, and removeChild DOM methods to dynamically add and remove text boxes. Actually, it adds and removes 'input' elements and then I assign 'text' to the 'type' attribute. I have another example where I add text boxes by modifying the 'innerHTML' property. Actually creating the nodes and adding them to the DOM tree like I do here is probably a much better way of handling this. I'm not sure why people so often want or need to add text inputs with a client side script. I suppose it has something to do with forms that ask additional questions based on a previous response.

Anyway, clicking one button adds an input and clicking the other removes the last one added. I use a node list and pass the last element, 'length-1', to the removeChild method. At first, I thought I would just use the element reference returned by the createElement method for this. But that only works well for removing one node. Then I thought I would keep up with the nodes I create in an array (lol). I quickly realized that was absurd considering a node list would already be available.




Scripts