Write a JavaScript program to change the text of a paragraph on button click

Description: Create a button. When the visitor clicks it, the text of a paragraph changes.

Hint:

  • Select both elements with getElementById().
  • Add a click listener to the button.

Change the text on button click

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Change text</title>
</head>
<body>
  <p id="message">Old text</p>
  <button id="btn">Change text</button>

  <script>
    const message = document.getElementById("message");
    const btn = document.getElementById("btn");

    btn.addEventListener("click", () => {
      message.textContent = "The text was changed!";
    });
  </script>
</body>
</html>

Output:

Output in the browser

The text was changed!

How it works

  • The result shown here is the page after the click. At the start it shows “Old text”.
  • textContent changes the text of the paragraph, and the page does not reload.

Read HTML DOM and DOM EventListener.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.