How to add and remove html elements dynamically using jquery

  1. Previous
  2. Next
  3. Recent

    1. Signs 'He' May be Cheating on You
    2. 7 Vows of Hindu Marriage - Know What 'Saat Vachans' Mean
    3. RuPay vs Visa vs Mastercard vs American Express- A Comparison
    4. What is RuPay? Everything You Need to Know About India's Domestic Payment System!
    5. Top 10 Online Portals to Find a High Paying Job in India
    6. Top Indians who Revolutionized the IT Sector in India
    7. 8 Initiatives by Narendra Modi that Could Change the Future of the Nation
    8. 8 Work-from-home Jobs for Housewives, Students, and Part timers
    9. Complete Company Registration Process in India - Explained
    10. Change Name in India in 5 Steps - Filing Affidavit, Newspaper Ad & Gazette Notification

While developing a dynamic website, a forum or a social media site you might want to generate HTML elements in runtime. As we see in Facebook, hundreds of comments are posted on an update. Every time someone post a comment, a new comment box is generated dynamically.

How its done? A new HTML element can be added using 2 ways: JavaScript and jQuery. JS code is lengthy, but jQuery code is simple and concise.

Here is a simple code that generate HTML elements dynamically using jQuery,

The HTML Code


<input type='button' value='Add Input box' id='add1'/>
<input type='button' value='Remove Input box' id='remove1'/>
<div id='space'></div>

The jQuery code


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<script language='Javascript'>

$('#add1').click(function(){
 $('#space').append("<input type='text' placeholder='Im here' />");
 });

$('#remove1').click(function(){
 $("input[type='text']").remove();
 });

</script>

When ‘add1’ button is clicked, a new textfield is added inside the ‘space’ div. And when ‘remove1’ is clicked, all the added html elements are cleared.

blog comments powered by Disqus