Javascript - innerHTML property - JavaScript Tutorial

Javascript - innerHTML property

BLUF: This tutorial on Javascript - innerHTML property provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: Javascript - innerHTML property

Understanding Javascript - innerHTML property is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

  • javascript innerHTML
  • Example of innerHTML property

The innerHTML attribute serves as a means to generate dynamic HTML content within an HTML document.

It is primarily utilized in web pages to create dynamic HTML elements, including registration forms, comment sections, hyperlinks, and more.

Example of innerHTML property

In this instance, we will construct an HTML form that is triggered when the user clicks on the button.

In this instance, we are programmatically generating the HTML form within the div element that has the identifier mylocation. We determine this location by invoking the document.getElementById function.

Example

<script type="text/javascript" >

function showcommentform() {

var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows='5' cols='80'></textarea>

<br><input type='submit' value='Post Comment'>";

document.getElementById('mylocation').innerHTML=data;

}

</script>

<form name="myForm">

<input type="button" value="comment" onclick="showcommentform()">

<div id="mylocation"></div>

</form>

Output of the above example

Show/Hide Comment Form Example using innerHTML

Example

<!DOCTYPE html>

<html>

<head>

<title>First JS</title>

<script>

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/>

<textarea rows='5' cols='70'></textarea><br><input type='submit' value='Post Comment'/></form>";

if(flag){

document.getElementById("mylocation").innerHTML=cform;

flag=false;

}else{

document.getElementById("mylocation").innerHTML="";

flag=true;

}

}

</script>

</head>

<body>

<button onclick="commentform()">Comment</button>

<div id="mylocation"></div>

</body>

</html>

Output of the above example

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience