H.dev

innerHTML

Manipulating Content

Now that we know how to select elements using methods like getElementById(), what can we actually do with them?

The most common action is reading or changing the content inside the element. We do this using the innerHTML property.

Reading Content

You can use innerHTML to see exactly what is inside an HTML tag.

HTML:

<div id="greeting-box">Hello <strong>World</strong>!</div>

JavaScript:

let box = document.getElementById("greeting-box");
console.log(box.innerHTML); 
// Outputs: "Hello <strong>World</strong>!"

Notice that innerHTML returns exactly what it says: the inner HTML. It includes the <strong> tags!

Changing Content

You can also assign a brand new string to innerHTML to completely replace the content of that element.

let box = document.getElementById("greeting-box");

// Replacing the content
box.innerHTML = "Welcome to my website!";

Rendering HTML Tags

The true power of innerHTML is that if you pass HTML tags in the string, the browser will actually render them!

let box = document.getElementById("greeting-box");

// The browser will render this as a real heading and paragraph!
box.innerHTML = "<h2>Success!</h2><p>Your account is created.</p>";

💡 Himanshu's Tip:

Security Warning: Never use innerHTML to display data that a user typed into an input field (like a comment box). Malicious users can type actual <script> tags into the comment box, and innerHTML will execute their code! This is called an XSS (Cross-Site Scripting) attack. Use textContent or innerText instead for user data.

Interview Questions

  1. What is the difference between innerHTML and textContent?
  2. Does assigning a new string to innerHTML append the text, or completely replace the existing text?
  3. Why is using innerHTML considered a security risk when handling user-submitted data?

Design & Developed by Himanshu Dubey © 2026