How to add and remove div dynamically in jQuery

In this tutorial I will explain you how to add and remove div dynamically in jQuery. The entire scenario can be understood with the help of a small program. We will create a container in the form of a DIV element. We will put two text box inside the DIV and two button ousite the div to add and remove the div using jQuery. Now create a folder name Test in your localhost and create index.php file inside the folder. You need to add jQuery CDN on the top of the you file to load jQuery.

Below are the code. Include the code inside the index.php file

<!doctype html>
<script src=""></script>
       var counter = 2;
                     var newTextBoxDiv = $(document.createElement('div')).attr("id",'TextBoxDiv' + counter);
                     newTextBoxDiv.after().html('<label>Deal </label> '+counter+'<br><input type="text" id="textbox'+counter+'" name="v_deals[]"  class ="form-control" value=""><br><label>Location</label><br> <input type="text" id="textbox'+counter+'" name="v_location[]"  class ="form-control" value="">');
       $("#removeButton").click(function () {
                      alert("No more textbox to remove");
                      return false;
              $("#TextBoxDiv" + counter).remove();

       <div id='TextBoxesGroup'>
       <label>Deal 1</label><br>
       <input type="text" id="textbox" name="v_deals[]"  class ="form-control" value=""><br>
       <input type="text" id="textbox" name="v_location[]"  class ="form-control" value="">
       </div><br><input type="button" class = "btn btn-primary" id="addbutton" value="Add DIV"><br>
       <input type="button" class = "btn btn-primary" id="removeButton" value="Remove DIV"><br><br>

Now run copy and paste the following URL in your browser. http://localhost/Test

You can add and remove the DIV dynamically.

Hope this small articale will help you to understand how to add and remove div dynamically in jQuery.

  • Paul Bowden

    Morning – I get Syntax Error on Line 43

    • Ricky Negi

      I have updated the code again check and let me know

  • Paul Bowden

    newTextBoxDiv.after().html(‘Deal ‘+counter+’

  • Paul Bowden

    YAY that’s better – one thing, the first time you click Add Div it says Deal 1 the same as the original?