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

1

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

But now, in addition, I need something to check if this class is active, if it is, I wanted to leave the body tag of the theme with a " overflow:hidden ", if not " overflow:auto ". / p>     

asked by anonymous 28.11.2016 / 08:01

2 answers

3

To do this you can use jQuery's .hasClass () method 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><divclass="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>
    
28.11.2016 / 08:48
1

With javascript you can get classes using element.className , where is returned a string with the classes of the element, and verify the existence of some with indexOf.

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