JS DOM: Button to Switch to Dark Theme

By Xah Lee. Date: . Last updated: .

Press the following buttons to toggle dark theme.

Code

<p><button id="buttonBlack" type="button">Dark Theme</button>
<button id="buttonWhite" type="button">Light Theme</button></p>
"use strict";
{
    const buttonWhite = document.getElementById("buttonWhite");
    if (buttonWhite === null)
        throw new Error("id buttonWhite missing");
    const buttonBlack = document.getElementById("buttonBlack");
    if (buttonBlack === null)
        throw new Error("id buttonBlack missing");
    buttonWhite.addEventListener("click", () => {
        document.body.style.color = "black";
        document.body.style.backgroundColor = "white";
    });
    buttonBlack.addEventListener("click", () => {
        document.body.style.color = "white";
        document.body.style.backgroundColor = "black";
    });
}