JavaScript – Change Text

JavaScript can change text of an element such as <p> or <h1>.

The following example finds two elements using the getElementById() function and changing their innerHTML attributes.

<html>
<head>
	
</head>
<body>

<h1 id="heading">Title</h1>
<p id="text">Text Goes Here</p>

<script>
var h = document.getElementById('heading');
var t = document.getElementById('text');
h.innerHTML = "Fancy Title";
t.innerHTML = "This is a fancy page with fancy info.";
</script>

</body>
</html>

The elements need id attribute for this to work:

<h1 id="heading">Title</h1>
<p id="text">Text Goes Here</p>

Notice that the id is set inside the opening tag of the element. You’ve seen this type of thing before with links and images.

To find an element whose id is “heading,” you use this command:

document.getElementById("heading")

To change the text of this heading, you have to modify its innerHTML attribute. The innerHTML is what comes between the tags:

Here’s how to change the innerHTML to just “abc”:

document.getElementById('heading').innerHTML = "abc";

You can save this object as a variable to use it later.
(When you use the  “var” keyword in JavaScript, you are declaring a variable name for the first time. The variable name is “myHeading” in the example below.)

var myHeading = document.getElementById("heading");

Now you can change the innerHTML of this object:

myHeading.innerHTML = "This is some new text.";

Where to put your JavaScript code?

This type of example will stop working if you put the JavaScript code before the HTML elements – your JavaScript would be trying to find and modify elements that don’t exist yet!

Notice that the example at the beginning of the page puts the JavaScript inside <script></script> tags, and those tags are at the end of the <body></body> section of your HTML page.

This works fairly well when you have code that needs to run as soon as the website loads.