I love it when magicians conjure things out of thin air. A dove, a rabbit you name it and it’s there. Sure they have their tricks but what’s amazing is how it’s presented.

As web developers, sometimes we are required to conjure elements and add them to the DOM. Be it  an error span or an addition textbox or an additional div, using our wand (jQuery) we can perform this trick with ease.

Powerful wizards can even perform magic without wands (using only JavaScript).

How to perform this WAND-LESS magic see here.

Let me  first define our trick, so we know exactly what we are to do. :
We will add a textbox to a div every time a button is clicked.

Lets have our DOM ready.

Nothing fancy here. We have an empty div and a button. So we have two parts of our trick in place: a button and a div. We have also kept our wand ready. Pretty neat, we are all set to start our trick.

First listen for the button click. We will need a magic spell ‘.on()’.

We are using jQuery’s ‘.on()’ method to handle the ‘click’ event on our button ‘btn-add-textbox’.

Now that we are listening for a click, what should we do when the user clicks? Add a text box! Time for another magic spell ‘.append()’.

‘.append()’ will insert content to the end of our div (https://api.jquery.com/find/)

Thats it! we append a textbox to our div ‘div-add-textbox-here’. So every time a user clicks on the button a text box will be added to the div.

We can do a few more tricks here like, limiting the number of textboxes to ten.

‘.length’ returns the number of elements currently matched (https://api.jquery.com/length/)

‘.find()’ method will get descendants and filter the elements we want (https://api.jquery.com/find/)

So we ask jQuery to find all inputs (textboxes) inside our div. And if the number of textboxes (.length will give the count) is less than 10 only then will we add another textbox. Neat little trick rite?.

We can use this same trick to add ‘options’ to ‘select’ or add any other element to the DOM.

With your wand (jQuery) and a few magic spells we can do all possible tricks.

Get full code on github

SiteLock