Web development
Responding to a Button Click
Updated Oct 28, 2026
A button can listen for a click and update text in the document. Place the script after the elements or wait until the document is ready. Confirm that the selector finds the expected button before reg
What you’ll learn
Learn to apply responding to a button click in a practical situation.
Explanation
A button can listen for a click and update text in the document. Place the script after the elements or wait until the document is ready. Confirm that the selector finds the expected button before registering the event. Use textContent for ordinary text.
Button អាចស្ដាប់ព្រឹត្តិការណ៍ click និងប្ដូរអត្ថបទ។ ត្រូវឱ្យធាតុ HTML មានរួចមុន script ជ្រើសវា ហើយប្រើ textContent សម្រាប់អត្ថបទធម្មតា។
Worked example
HTML: <button id="greet">Greet</button><p id="message"></p>. JavaScript: document.querySelector("#greet").addEventListener("click", () => { document.querySelector("#message").textContent = "Hello!"; });
Practice
- What should you check if the selector returns null?
- Apply the idea to an example of your own and explain your choice.
Answers and guidance
Show answers / បង្ហាញចម្លើយ
- Check the ID spelling and that the element exists before the script runs.
- Answers vary. Compare your example with the explanation and check each step.
Quick recap
A button can listen for a click and update text in the document.