Menu Close

How to append data to div element using JavaScript

How to append data to div element using JavaScript

To append form submit data to any <div> or <section> element we need to use manipulation techniques. Initially we need to create one empty div element where we can append the data. Then we can append the entered input value to the inner text of that specific div by using the simple JavaScript codes.

Here, I share the code snippet for simple data append model with example.

<form> 
    <div class="form-group">
        <div class="input-group mb-2">
            <div class="input-group-prepend">
                <span class="input-group-text" id="inputGroup-sizing-default">Enter Input</span>
            </div>
            <input type="text" class="form-control" id="e_input">
        </div>
    </div>

    <div class="form-group text-center"> 
        <button id="add-data" class="btn btn-primary btn-lg" type="button"> 
            Add Name 
        </button> 
    </div> 
</form> 

<h3>List of Data:</h3> 
<div id="mydata"></div>

<script> 
    function append_to_div(div_name, data){ 
        document.getElementById(div_name).innerText += data; 
    } 

    document.getElementById("add-data") 
            .addEventListener('click', function() { 
        var e_input = document.getElementById("e_input"); 
        var value = e_input.value.trim(); 

        if(!value){
            alert("Input field can't be empty!"); 
        } else {
            append_to_div("mydata", value+"\n"); 
        }
        e_input.value = ""; 
    }); 
</script> 

Output

Enter Input

List of Data:

Posted in HTML, JavaScript

You can also read...