Change HTML Text with JavaScript

Change HTML Text with JavaScript
Code Snippet:Function to Update Text
Author: Dennis Good
Published: January 20, 2024
Last Updated: January 22, 2024
Downloads: 442
License: MIT
Edit Code online: View on CodePen
Read More

This code demonstrates how to change HTML text with JavaScript. It works by defining a message variable and a function, ‘updateMessage,’ which updates the text content of an HTML element with the id ‘message-text.’ It’s helpful for dynamically updating text on a webpage.

You can use this code on your website to dynamically update text, such as announcements, messages, or notifications. It offers real-time information delivery to your visitors, enhances user experience, and keeps your content relevant without requiring manual edits.

How to Create Change HTML Text with JavaScript

1. Ensure you have the HTML structure in place, including the target element with an ID that you want to update. In our example, we have an <h2> element with the ID “message-text.”

<h1>Update Text Function</h1>
<h2 id="message-text">Welcome to our site!</h2>

2. You can style your webpage as desired. (Optional)

body {
  text-align: center;
  font-family: arial, helvetica, san-serif;
  background-color: #3D3E6F;
  color: #ffffff;
 line-height: 3;
}

3. Now, let’s dive into the JavaScript part. The JavaScript code is responsible for updating the text dynamically.

// Creates a variable called message which will hold a new message
var message = 'This is the new message being updated with Javascript!';

// Create a function to update an element with id message-text
function updateMessage() {
  var el = document.getElementById('message-text');
  el.textContent = message;
}

// Calls the function
setTimeout(updateMessage , 2000);

You can modify the message variable with the text you want to display and adjust the delay in setTimeout as per your preferences. The code will automatically update the content of the targeted HTML element.

That’s all! hopefully, you have successfully created Change HTML text with JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X