0
0
JavascriptHow-ToBeginner · 3 min read

How to Change innerHTML in JavaScript: Simple Guide

To change the content inside an HTML element using JavaScript, select the element and set its innerHTML property to a new string. For example, element.innerHTML = 'New content'; replaces the existing HTML inside that element.
📐

Syntax

The innerHTML property of an HTML element lets you get or set the HTML content inside that element.

  • element: The HTML element you want to change.
  • innerHTML: The property that holds the HTML content inside the element.
  • = 'new content': Assigning a new string replaces the current content.
javascript
element.innerHTML = 'new content';
💻

Example

This example shows how to change the text inside a <div> element when a button is clicked.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Change innerHTML Example</title>
</head>
<body>
  <div id="message">Hello, world!</div>
  <button onclick="changeContent()">Change Text</button>

  <script>
    function changeContent() {
      const div = document.getElementById('message');
      div.innerHTML = 'You clicked the button!';
    }
  </script>
</body>
</html>
Output
Initially shows 'Hello, world!' in the div. After clicking the button, the div text changes to 'You clicked the button!'
⚠️

Common Pitfalls

Some common mistakes when using innerHTML include:

  • Using innerHTML on elements that do not exist or are not selected correctly, causing errors.
  • Setting innerHTML with untrusted user input can cause security risks like cross-site scripting (XSS).
  • Replacing innerHTML removes all child elements and event listeners inside the element.
javascript
/* Wrong: selecting element incorrectly */
const div = document.getElementById('wrongId');
if(div) {
  div.innerHTML = 'New content'; // Avoid error if div is null
}

/* Right: correct selection */
const divCorrect = document.getElementById('message');
divCorrect.innerHTML = 'Safe new content';
📊

Quick Reference

Remember these tips when using innerHTML:

  • Use document.getElementById or other selectors to get the element.
  • Assign a string to innerHTML to change content.
  • Avoid inserting untrusted HTML to prevent security issues.
  • Changing innerHTML replaces all existing content inside the element.

Key Takeaways

Use element.innerHTML = 'new content' to change the HTML inside an element.
Always select the correct element before changing innerHTML to avoid errors.
Avoid inserting untrusted HTML to prevent security risks like XSS.
Changing innerHTML removes all existing child elements and event listeners inside the element.
Use innerHTML for simple content changes; consider other methods for complex updates.