JavaScript DOM
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
clicklistener 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”.
textContentchanges the text of the paragraph, and the page does not reload.
Read HTML DOM and DOM EventListener.
Write a JavaScript program to switch dark mode on and off
Description: Create a button that switches the page between light and dark colours.
Hint:
- Make a CSS class
.darkwith dark colours. - Use
classList.toggle("dark")on the body.
Toggle dark mode
<style>
body { background: white; color: black; }
body.dark { background: #1e1e1e; color: #f5f5f5; }
</style>
<button id="toggle">Toggle dark mode</button>
<script>
document.getElementById("toggle").addEventListener("click", () => {
document.body.classList.toggle("dark");
});
</script>
Output:
Output in the browser
The page after one click (dark class added).
How it works
classList.toggle("dark")adds the class if it is missing, and removes it if it is there.- The CSS rule
body.darkthen changes the colours. Each click switches again. - The box above shows the dark state.
Read HTML DOM and CSS Variables.