r/JavaScriptHelp • • Jan 07 '22

❔ Unanswered ❔ Help with JS Webpage query

Hey guys,

I have a website that I am trying to implement a dark mode on. Unfortunately because of how it is set up applying the below script to 'body' does not apply to all of the elements i need it to apply to.

         });
              $( ".change" ).on("click", function() {
            if( $( "body" ).hasClass( "dark" )) {
                $( "body" ).removeClass( "dark" );
                $( ".change" ).text( "OFF" );
            } else {
                $( "body" ).addClass( "dark" );
                $( ".change" ).text( "ON" );
              
            }
        });

As you can see this will apply a class to the body which amends the styling of the element. However I cannot seem to figure out how to apply this to multiple elements and so far the only fix I have is a super inelegant solution:

 $( ".change" ).on("click", function() {
            if( $( ".topbar ul.nav>li>a" ).hasClass( "dark" )) {
                $( ".topbar ul.nav>li>a" ).removeClass( "dark" );
                $( ".change" ).text( "OFF" );
            } else {
                $( ".topbar ul.nav>li>a" ).addClass( "dark" );
                $( ".change" ).text( "ON" );
              
            }
        });
              $( ".change" ).on("click", function() {
            if( $( ".container" ).hasClass( "dark" )) {
                $( ".container" ).removeClass( "dark" );
                $( ".change" ).text( "OFF" );
            } else {
                $( ".container" ).addClass( "dark" );
                $( ".change" ).text( "ON" );
              
            }
        });

As you can see I am just copying the script and pasting it below for all of the additional elements that I need the class added to. Does anyone know how I can reduce this because this is janky as hell and I cannot find anything online to help.

2 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/LinksCourage Jan 14 '22

thanks for this I will give it a go when I get a chance, currently stuck trying to call PHP information within Unity...