- Home
- /
- JS innerHTML
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- JS innerHTML
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
Original content goes here
Example JavaScript
let myDiv = document.getElementById("myDiv");
myDiv.innerHTML = "Updated by Learn With Arshyan
";
This code completely replaces the old <p>
content inside the <div>
with new content.
Key Features
Feature | Description |
---|---|
Reads content | You can get the current HTML inside an element. |
Replaces content | When you set innerHTML , it replaces all existing content in the element. |
Accepts HTML | You can insert full HTML elements (not just plain text). |
Removes previous handlers | Any 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 = "";
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
.