Edit Template
Edit Template

JavaScript innerHTML

The innerHTML property is used to get or set the HTML content inside an element. It allows you to read what’s between the tags of an element or completely replace it with new HTML.

Syntax

				
					element.innerHTML         // Get the HTML content
element.innerHTML = "..." // Set new HTML content

				
			

Example HTML

				
					<div id="myDiv">
  <p>Original content goes here</p>
</div>

				
			

Example JavaScript

				
					let myDiv = document.getElementById("myDiv");
myDiv.innerHTML = "<p>Updated by Learn With Arshyan</p>";

				
			

 This code completely replaces the old <p> content inside the <div> with new content.

Key Features

FeatureDescription
Reads contentYou can get the current HTML inside an element.
Replaces contentWhen you set innerHTML, it replaces all existing content in the element.
 Accepts HTMLYou can insert full HTML elements (not just plain text).
Removes previous handlersAny attached JavaScript event listeners will be lost when content is replaced.

Caution:

Using innerHTML can introduce security vulnerabilities if you insert unsanitized user data (e.g. from a form or API). Malicious users can inject scripts like this:

				
					element.innerHTML = "<script>alert('Hacked');</script>";

				
			

Never use innerHTML with untrusted data. Use textContent or sanitize inputs properly if needed.

Summary

  • innerHTML lets you get or set the full HTML inside an element.

  • It’s useful for inserting dynamic content or templates.

  • Always use it with caution when working with user data.

  • If you just want to insert plain text, prefer textContent.

Scroll to Top