Zed-King Institute

    JavaScript Change Text on Button Click Example

    hardJavaScript eventsHTML

    The first step into JavaScript: making the page react when the user clicks.

    The question

    Create a button with id "btn" and an empty paragraph with id "msg". When the button is clicked, JavaScript must put the text "JavaScript is working!" inside #msg.

    The code

    index.html

    <button id="btn">Click me</button>
    <p id="msg"></p>
    
    <script>
    document.getElementById("btn").addEventListener("click", function () {
      document.getElementById("msg").textContent = "JavaScript is working!";
    });
    </script>

    Result

    How it works

    1. 1document.getElementById("btn") finds the button by its id.
    2. 2addEventListener("click", function () { … }) runs the function on every click.
    3. 3Setting textContent on #msg replaces the paragraph's text.

    Common mistakes

    • Placing the script before the button in the HTML, so getElementById finds nothing.
    • Writing getElementByID (capital D) — JavaScript names are case sensitive.

    Now solve a similar question yourself

    A new HTML / CSS / JS question every time, checked instantly.

    Practice questions

    More in JavaScript events