The Wayback Machine - https://web.archive.org/web/20211024115212/https://www.geeksforgeeks.org/how-to-append-data-to-div-element-using-javascript/
Skip to content
Related Articles

Related Articles

Improve Article

How to append data to <div> element using JavaScript ?

  • Difficulty Level : Expert
  • Last Updated : 11 Oct, 2019
Geek Week

To append the data to <div> element we have to use DOM(Document Object Model) manipulation techniques. The approach is to create a empty <div> with an id inside the HTML skeleton. Then that id will be used to fetch that <div> and then we will manipulate the inner text of that div.

Syntax:

document.getElementById("div_name").innerText += "Your Data Here";

Example:




<!DOCTYPE html> 
<html> 
  
<head> 
    <title>
        How to append data to
        div using JavaScript ?
    </title> 
      
    <meta charset="utf-8"> 
      
    <meta name="viewport"
        content="width=device-width, initial-scale=1"> 
      
    <link rel="stylesheet" href= 
  
</head> 
  
<body> 
    <div class="container"> 
        <h1 style="text-align:center;color:green;"> 
            GeeksforGeeks 
        </h1> 
          
        <hr>
          
        <form> 
            <div class="form-group"> 
                <label for="">Enter Your Name:</label> 
                <input id="name" class="form-control"
                    type="text"
                    placeholder="Input Your Name Here"> 
            </div>
              
            <div class="form-group text-center"> 
                <button id="my_button"
                    class="btn btn-outline-success btn-lg"
                        type="button"> 
                    Add Name 
                </button> 
            </div> 
        </form> 
          
        <h3>List of Names:</h3>
        <div id="my_div"></div>
    </div> 
      
    <script>
        function append_to_div(div_name, data){
            document.getElementById(div_name).innerText += data;
        }
          
        document.getElementById("my_button")
                .addEventListener('click', function() {
              
            var user_name = document.getElementById("name");
            var value = user_name.value.trim();
              
            if(!value)
                alert("Name Cannot be empty!");
            else
                append_to_div("my_div", value+"\n");
              
            user_name.value = "";
        });
    </script>
      
</body> 
  
</html>

Output:

  • Before Adding the Data:
    output_before
  • After Adding the Data:
    output_after

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :