'Javascript: Change element class if button has a certain value [closed]


        <div class="main-div main-div2"> <!-- IF up to date, main-div3 -->
          <button id="update-btn" class="btn update-btn"> 
              Up to date
          </button>
        </div>

I want to make it so if update-btn has a value of "Up to date", change the div class from "main-div main-div2" to "main-div main-div3". Otherwise, if it's any other value, change it to "main-div main-div2"

What kind of loop would be good for this Javascript function too if I want it to be checking constantly?

Thank you.



Solution 1:[1]

there are many method to do it, here is the basic idea that you can get it done.

var btnText = document.getElementById("update-btn").innerText
var divClass = document.getElementById("outer-div")

if(btnText == "Up to date"){
    divClass.classList.remove("main-div2");
    divClass.classList.add("main-div3");
}else{
    divClass.classList.remove("main-div3");
    divClass.classList.add("main-div2");

}
.main-div2{
  background-color:red;
}

.main-div3{
  background-color:blue;
}
 <div id="outer-div" class="main-div main-div2">
   <button id="update-btn" class="btn update-btn"> 
     Up to date
   </button>
</div>

checkout the above snippet, its checking the text In if condition and sets up the class for parent div according to the text in the button, you can read more about adding and removing class from here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CodeBug