Search code examples
javascripthtmldynamicelementcreation

How to create an element dynamically in an html page using javascript?


I am learning to create an element dynamically in an html page using javascript. In this code I am trying to create a simple "h6" inside "div-1".

<!DOCTYPE html>
    <header>
        <meta charset="utf-8">
    </header>
    <body>
        <button onclick="constructElement()">click</button>
        <div id="div-1"></div>

        <script>
            function constructElement(){
                var elem = document.createElement("h6");
                elem.innerText("Dynamically added text.")
                document.getElementById("div-1").appendChild(elem);
            }
        </script>
    </body>
</html>

Solution

  • there are two mistakes in your code the first is that you used wrong "id" name div-1 instead of div1 also, innerText isn't a function

    this is the code after the fix :)

    <header>
      <meta charset="utf-8">
    </header>
    
    <body>
    
      <button onclick="constructElement()">click</button>
    
      <div id="div-1">
    
      </div>
    
      <script>
        function constructElement() {
          var elem = document.createElement("h6");
          elem.innerText = "Dynamically added text."
          document.getElementById("div-1").appendChild(elem);
        }
      </script>
    </body>