How to check if an element has a class, or is with an "active" class

Asked

Viewed 7,745 times

1

I used the .toggleClass() in a div, after clicking on a button, activate the class "menu-active", if clicked again, it removes it. So far so good.

Only now beyond that, I need something to check that class is active, if it is, I’d like to leave the tag body of the theme with a "overflow:hidden", if not "overflow:auto".

2 answers

3

To do this you can use the method .hasClass() jQuery as follows:

if ($(".menu").hasClass("menu-active")) {
    // Faz algo aqui
}

Here is an example below:

if ($(".menu").hasClass("menu-active")) {
    $(".menu-active").css('color', 'red');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<div class="menu menu-active">Se o elemento ".menu" tiver a class "menu-active", muda o texto para vermelho.</div>
<div class="menu">Se não tiver, não faz nada.</div>

  • I don’t know much about js, but I looked at google, and in my case I think . hasClass() doesn’t work. Because like I said, I used . toggleClass() on my div, and I needed you to check if the class was active by following the toggleClass "add/remove", you know? Well, from what I’ve seen hasClass doesn’t work for that.

  • 2

    @Ericki doesn’t know what exactly you researched, but toggleClass is equivalent to addClass and removeClass in jQuery. Therefore, hasClass should work, it will simply check whether or not the element has a certain class.

  • 2

    @Ericki, of course the .hasClass() will serve in your case, maybe you have gotten confused for you because it takes another selector to use it, and as you have not posted any content of your html, our friend suggested something that was more logical...but basically you would have to add the class menu in your div and work to menu-active as it has already done, and your if with the .hasClass will work perfectly...

1

With javascript it is possible to get the classes using element classname., where a string is returned with the classes of the element, and check the existence of some with indexef.

  var classes = document.getElementById('div1').className;
  if (classes.indexOf('menu-active') !== -1){} // diferente de -1 é encontrado

Browser other questions tagged

You are not signed in. Login or sign up in order to post.