How to create HTML element using Javascript/jQuery

Javascript Post
Follow us

In this article, we are going to see how to create HTML elements using javascript and jquery.

Using Javascript:

First, we have to create an element and then have to append it to the parent element.

To create an element Javascript has function called document.createElement().

Example: In this example, we create a form input element.

<form id="myForm" method="post"></form>

The above element is a parent element.

var inputElement = document.createElement('input');
inputElement.setAttribute('type','text');

Now its time to append this element to the form element.

var formElement = document.getElementById('myForm');
formElement.appendChild(inputElement);
<html>
  <head>
    <script>
      function createElem(){
        var inputElement = document.createElement('input');
		inputElement.setAttribute('type','text');
        var formElement = document.getElementById('myForm');
		formElement.appendChild(inputElement);
      }
    </script>
  </head>
 <body>
   <button onclick="createElem();">Create Element </button>
   <form id="myForm" method="post"></form>
 </body>
</html>
Using jQuery:

As jQuery is fun it makes the job easy. Here is an example.

var inputElement = "<input type='text'>";
$('#myForm').append(inputElement);
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
      function createElem(){
        var inputElement = "<input type='text'>";
		$('#myForm').append(inputElement);
      }
    </script>
  </head>
 <body>
   <button onclick="createElem();">Create Element </button>
   <form id="myForm" method="post"></form>
 </body>
</html>

Leave a Comment

Your email address will not be published. Required fields are marked *