Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make a function that checks if an element has a certain class and if true, runs a separate function?

I’m making a site for me to experiment and go out of my comfort zone and I’m trying to add a button that runs a different function based on whether or not it’s in dark or light theme using javaScript. I want it to work like this:

if elementClass == "dark" 
run function 1
else if elementClass == "light" 
run function 2

This is my current code
html:
<button id="fullscreen" class="fullscreen dark" onclick='checkClass()'> Fullscreen </button>

script:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function checkClass() {
    if ($('.fullscreen').hasClass('dark') === true) {
        openFullscreenDark()    
    } else if ($('.fullscreen').hasClass('light') === true){
        openFullscreenLight()   
    }
}   

The openfullscreen functions are working, however I don’t know how to properly check for classes as well as run a function in a function.

The if statements I found in another post and I don’t know how to use jQuery.

Is this possible to do? If so how?

>Solution :

You can rewrite the checkClass() function with vanilla JS like this:

function checkClass() {
    if (document.querySelector('.fullscreen').classList.contains('dark') === true) {
        openFullscreenDark()    
    } else if (document.querySelector('.fullscreen').classList.contains('light') === true){
        openFullscreenLight()   
    }
} 

Since contains() returns a boolean, you can also simplify it to:

function checkClass() {
    if (document.querySelector('.fullscreen').classList.contains('dark')) {
        openFullscreenDark()    
    } else if (document.querySelector('.fullscreen').classList.contains('light')){
        openFullscreenLight()   
    }
} 

Since you are only checking one element, you could also use getElementById() like this:

function checkClass() {
    if (document.getElementById('fullscreen').classList.contains('dark')) {
        openFullscreenDark()    
    } else if (document.getElementById('fullscreen').classList.contains('light')){
        openFullscreenLight()   
    }
} 

As you can see, there are many different ways to do this in vanilla JS, but they all do the same thing.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading