Javascript: Change element class if button has a certain value

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

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.

1 answer

  • answered 2022-05-07 06:23 CodeBug

    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"){
     <div id="outer-div" class="main-div main-div2">
       <button id="update-btn" class="btn update-btn"> 
         Up to date

    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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum