Store the initial class of HTML and return it

0

I am trying to store the initial value of a class and return it to a conditional ternary operator when it does not meet the conditions

I tried something like:

  function toggleDarkLight() {
  var body = document.getElementById("body");
  var currentClass = body.className;

  var almacenaclaseincial= [claseinicial=document.getElementById("body")];

  body.className = currentClass == "sidebar-fixed dark-mode" ? "sidebar-fixed light-mode" : 
                   currentClass == "sidebar-fixed dark-mode sidebar-slim" ? "sidebar-fixed light-mode sidebar-slim" :
                   currentClass == "sidebar-fixed dark-mode sidebar-overlay" ? "sidebar-fixed light-mode sidebar-overlay" :
                   claseinicial;}

The HTML is quite extensive but I just need to modify

<body class="sidebar-fixed dark-mode" id="body"></body>
    
asked by alec_brac 25.07.2018 в 01:30
source

2 answers

0

To achieve what you want, you only need to capture the class before changing it. Something like this:

function toggleDarkLight() {
  var body = document.getElementById("body");
  var currentClass = body.className;
  console.log(currentClass);      

  body.className = currentClass == "sidebar-fixed dark-mode" ? "sidebar-fixed light-mode" : 
                   currentClass == "sidebar-fixed dark-mode sidebar-slim" ? "sidebar-fixed light-mode sidebar-slim" :
                   currentClass == "sidebar-fixed dark-mode sidebar-overlay" ? "sidebar-fixed light-mode sidebar-overlay" :
                   currentClass;
  console.log(body.className);
}
toggleDarkLight();
<body class="sidebar-fixed dark-mode" id="body">Test</body>
    
answered by 25.07.2018 в 01:44
0

I recommend you look for the list of classes with classList() and then compare. In this way the possibility of having other classes with the className()

is not obvious
function toggleDarkLight() {
  var body = document.getElementById("body");
  var currentClass = body.classList;
  console.log(currentClass);      
     if(currentClass.contains("sidebar-fixed") && currentClass.contains("dark-mode")){
       if((!currentClass.contains("sidebar-slim")) && (!currentClass.contains("sidebar-overlay"))){
          body.addClass("sidebar-fixed light-mode");
      }else{  
         if(currentClass.contains("sidebar-slim")){ 
            body.addClass("light-mode sidebar-slim");
         }
         if(currentClass.contains("sidebar-overlay")){ 
            body.addClass("light-mode sidebar-overlay");
          }
   }
}
toggleDarkLight();
    
answered by 25.07.2018 в 02:03