In this tutorial we will learn How To Change h1 Tag Text with JavaScript. We can use innerHTML property to change the text of any HTML tag. Other properties that can do the same include textContent property and innerText property.
Table of Contents
innerHTML property
innerHTML property sets or returns the inner content of HTML element.
In this example innerHTML property is used to change the text of h1 tag.
HTML Code
HTML Code is given below, in this code we have a h1 tag and a button tag with onclick event.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Change h1 Tag Text</title>
</head>
<body>
<h1 id="heading">Heading</h1>
<button onclick="changeH1Text()">Change Text!</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, in this code getElementById() method is used to select the h1 tag. While innerHTML property is used to update or change the inner text of the h1 tag.
<script>
function changeH1Text()
{
var heading = document.getElementById('heading');
heading.innerHTML = 'New Heading!';
}
</script>
textContent property and innerText property can also be used to change the text of h1 tag.
With textContent property
<script>
function changeH1Text()
{
var heading = document.getElementById('heading');
heading.textContent = 'New Heading!';
}
</script>
With innerText property
<script>
function changeH1Text()
{
var heading = document.getElementById('heading');
heading.innerText = 'New Heading!';
}
</script>
textContent and innerText properties can only change text of the selected tag while the innerHtml property can change the text as well as the HTML tags inside the element.
Demo
Video Tutorial
Watch video tutorial on How To Change h1 Tag Text in JavaScript.