We have seen how our wand (jQuery) can be used to Dynamically Add content to DOM. But then there are powerful wizards who do not like to use wands for such small tricks. Here is how you perform the same trick with pure magic (JavaScript).

First things first, lets start with our HTML

Simple HTML page. With an empty div (div-add-textbox-here), textboxes will be added to this div. A button (btn-add-textbox) to trigger the text box addition. And that’s about it.

Lets start with the magic.

First we summon the button (btn-add-textbox) and then tell the button to listen for a ‘click’. Next we will tell the button what to do when it hears a click.

We create a new element of type ‘input’ and do the following :

  • We need an input box so  we tell the element that it will be of type ‘text’.
  • Then tell the element that will be of class ‘magic-text-box’ (this is just for styling).
  • Lastly we tell the element what its value will be.

‘getDiv.children.length + 1’ = get a count of all elements inside ‘getDiv’ and add one to that count.

So on the first click, there are zero elements inside ‘getDiv’. Therefore 0 + 1 = 1, hence element will get value 1. So on and so forth.

Now we are done setting up our textbox, we add it to ‘getDiv’.

And that’s it. Of-course we can do lot of things here. Like we can restrict a user to add only 10 textboxes.

Here before adding a textbox we check if the number of elements inside getDiv (getDiv.children.length) is less then 10 only then we add the textbox.

Get full code on github