Improve your skills

September 27, 2016

How to Add or Remove HTML Element Dynamically in Javascript or JQuery


In this article, we will discuss about how to add or remove any html element dynamically in javascript or jquery.

We can easily add or remove any HTML elements like textbox, button, radio button etc. using JavaScript. JavaScript’s document object has a method called createElement() which can be used to create HTML elements dynamically.

First, we take a button(to add additional html element like textbox) or a textbox (default textbox) in body as show in below-

HTML:
<body style="background: #E0EDFA; text-align: center; margin-top: 250px;">
    <div id="dvAllTextbox">
        <input type="button" value="Add New Textbox" onclick="createTextbox();" /><br />
        <input type="text" /><br />
    </div>
</body>

After that, attach the jquery library link and write the below javascript code in head part as shown below-

JS:
<head>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        var i = 1;
        function createTextbox() {
            var div = document.createElement('DIV');
            div.innerHTML = "<input id='txt" + i + "' type='text' /><input id='btnRemove" + i + "' type='button' value='Remove' onclick='removeTextbox(this.id);' />"
            document.getElementById("dvAllTextbox").appendChild(div);
            i++;
        }

        function removeTextbox(id) {
            var newId = document.getElementById(id);
            newId.parentNode.parentNode.removeChild(newId.parentNode);
        }

    </script>
</head>

Now save the file and run on browser.

The function createTextbox() creates an HTML DIV element with a TextBox and a Button (to remove the TextBox) and then appends it to the Container DIV.

The function removeTextbox() simply removes the dynamically added DIV with TextBox and Button that was clicked.


Demo:






0 comments:

Post a Comment

Subscribe for Latest Update

Popular Posts