JavaScript inner html
The innerHTML property allows dynamic
HTML content to be written to an HTML document.
It is commonly used on web pages to generate dynamic HTML content, such as
registration forms, comment forms, and links.
Example of inner html property
In this example, we will create an HTML form when the user clicks the button.
In this example, we dynamically write the HTML form inside a div with the ID
"mylocation," identified using the document.getElementById() method.
Example
<!DOCTYPE html>
<html>
<head>
<title>Dynamically Create Form</title>
</head>
<body>
<div id="mylocation"></div>
<script>
// Get the div element with id "mylocation"
var locationDiv =
document.getElementById("mylocation");
// Create a new HTML form
var form =
document.createElement("form");
form.setAttribute("id", "myForm");
form.setAttribute("method", "post");
form.setAttribute("action", "#");
// Create form fields
var fieldName =
document.createElement("input");
fieldName.type = "text";
fieldName.name = "fieldName";
fieldName.placeholder = "Enter your location";
var fieldEmail =
document.createElement("input");
fieldEmail.type = "email";
fieldEmail.name = "fieldEmail";
fieldEmail.placeholder = "Enter your email";
var fieldSubmit =
document.createElement("input");
fieldSubmit.type = "submit";
fieldSubmit.value = "Submit";
// Append form fields to the form
form.appendChild(fieldName);
form.appendChild(document.createElement("br"));
form.appendChild(fieldEmail);
form.appendChild(document.createElement("br"));
form.appendChild(fieldSubmit);
// Append the form to the div
locationDiv.appendChild(form);
</script>
</body>
</html>
Output:
Before running the script:
<div id="mylocation"></div>
After running the script:
<div id="mylocation">
<form id="myForm" method="post"
action="#">
<input type="text" name="fieldName"
placeholder="Enter your location">
.
<input type="email" name="fieldEmail"
placeholder="Enter your email">
<input type="submit"
value="Submit">
</form>
</div>