Skip to content

Change innerHTML JavaScript

  • by

In JavaScript, you can change the content of an HTML element using the innerHTML property. Here’s an example of how to change the innerHTML of an element with the id of “myElement” to the string “Hello, world!”:

document.getElementById("myElement").innerHTML = "Hello, world!";

You can also use the innerHTML property to append HTML content to an element.

document.getElementById("myElement").innerHTML += "<p>This is a new paragraph.</p>";

use the += operator to append the HTML paragraph tag.

Change innerHTML JavaScript example

Simple example code.

<!DOCTYPE html>
<html>
  <head>
    <title>Change innerHTML example</title>
  </head>
  <body>
    <h1 id="myHeader">Welcome to my page</h1>
    <p id="myParagraph">This is some sample text.</p>
    <button id="myButton" onclick="changeContent()">Click me</button>
    
    <script>
    function changeContent() {
  
        let header = document.getElementById("myHeader");
        let paragraph = document.getElementById("myParagraph");
  
        // Change the innerHTML of the header element
        header.innerHTML = "Hello, world!";
  
        // Append a new paragraph
        paragraph.innerHTML += "<br><br>This is some additional text.";
    }
    </script>
  </body>
</html>

Output:

Change innerHTML JavaScript

How to change innerHTML every few seconds?

Answer: To change the innerHTML of an HTML element every few seconds using JavaScript, you can use the setInterval() method to run a function that changes the content of the element at a specified interval.

Here’s an example of how to change the innerHTML of an element with the id of “myElement” to a different string every 3 seconds:

<p id="myElement">This is some sample text.</p>

function changeContent() {
  let element = document.getElementById("myElement");
  let content = element.innerHTML;
  
  if (content === "This is some sample text.") {
    element.innerHTML = "This is some different text.";
  } else {
    element.innerHTML = "This is some sample text.";
  }
}

setInterval(changeContent, 3000);

Be cautious when using innerHTML as it can introduce security vulnerabilities if the added content is not properly sanitized. Using DOM manipulation methods (e.g. createElement, appendChild) is recommended instead as it provides better security and control.

Comment if you have any doubts or suggestions on this JS HTML topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading