Learn JavaScript for Web Development

JavaScript is most versatile languages to code applications for the browser, desktop, phone or tablet. Write program for client browser or web server. Build interactive web site with JavaScript.

JavaScript - innerHTML

The innerHTML property can be used to write the dynamic html on the html document.

It is used mostly in the web pages to generate the dynamic html such as registration form, comment form, links etc.

Example of innerHTML property

In this example, we are going to create the html form when user clicks on the button.

In this example, we are dynamically writing the html form inside the div name having the id mylocation. We are identifing this position by calling the document.getElementById() method.

<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><div rows='5' cols='80'></div>
<br><input type='submit' value='Post Comment'>";
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>


Show/Hide Comment Form Example using innerHTML

<!DOCTYPE html>
<title>First JS</title>
var flag=true;
function commentform(){
var cform="<form action='Comment'>Enter Name:<br><input type='text' name='name'/><br/>
Enter Email:<br><input type='email' name='email'/><br>Enter Comment:<br/>
<div rows='5' cols='70'></div><br><input type='submit' value='Post Comment'/></form>";
<button onclick="commentform()">Comment</button>
<div id="mylocation"></div>

Output of the above example