1

I want to change the css properties of many html objects (but in this example I only took body to simplify. My goal is to display dark mode if the current mode is light, or display light mode if current mode is dark. My javascript function does not work.

debug.html:

<!DOCTYPE html>
<html lang="en" dir="ltr">

  <head>

    <meta charset="utf-8">

    <link rel="stylesheet" href="debug.css">
    <script src="darkmode.js"></script>

  </head>

  <body id="bodyElem" class="my-body light-mode">

      <h1>Settings</h1>
      <p>Dark mode:</p>

      <button type="button" onclick="invertMode()">click</button>

  </body>

</html>

debug.css:

.my-body.light-mode{
  background-color: yellow;
}

.my-body.dark-mode{
  background-color: black;
}

darkmode.js:

function invertMode() {
  var body = document.getElementById("bodyElem");
  var currentClass = body.className;
  body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
}
Mike Delta
  • 726
  • 2
  • 16
  • 32
  • you can use queryselector – godfather Mar 24 '19 at 17:55
  • Just use document.body to get body obj. Them check classes with classList or/and className, to toggle or change or whatever body class. – keypaul Mar 24 '19 at 18:00
  • ok but it's an example, in my real code it's not body i need to acces like i did – Mike Delta Mar 24 '19 at 18:02
  • Ok so use just as godfather said, querySelector or querySelectorAll. if you Need it change a lot of elements the approach Is right, change class to the body, and use that class into css change descendant elements styles. – keypaul Mar 24 '19 at 18:04
  • my problem is that I have two classes in body but I do the `body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";` verification with only one class so it does not work but I don't know how to check it – Mike Delta Mar 24 '19 at 18:05
  • If you have more class on body use classList to check what class/es is in there, than change (add/remove) according to your Wish. https://stackoverflow.com/questions/5898656/test-if-an-element-contains-a-class – keypaul Mar 24 '19 at 18:11

1 Answers1

0

You will need to add an ID for the <body> tag to be able to find it using your code.

<body id="bodyElem" class="light-mode">

and access it using:

var body = document.getElementById("bodyElem");

If you need to access mutiple elements, you can use their CSS class name like:

document.getElementsByClassName("CLASSNAMEHERE");

then loop them all to apply the changes you need.

you will be using .classList.remove("CLASSNAME") to remove single class and .classList.add("CLASSNAME") to add single class to DOM element

Here is a complete sample fiddle: https://jsfiddle.net/j3o8Lt5k/1/