1

How to add 2 different classes using jquery?

I have this code:

<div id="divprincipal" class="divprincipal">
    <div id="div1" class="max"></div>
</div>

var clase1 = $('#hola').attr('class');
$(document).ready(function () {
    $("#hola").click(function () {
        $("#divprincipal").animate({
            height: "30px"
        }, 1000);
        $("#hola").addClass("min");
        alert(clase1);
        if (clase1 == "min") {
            $("#divprincipal").animate({
                height: "200px"
            }, 1000);
            $("#hola").addClass("max");
            alert(clase1);
        }
    });
});

I added an alert to know what's the current class and i keep returning the same class

4
  • 1
    You are changing the jQuery element, but not clase1 that's why Commented Jan 30, 2014 at 21:46
  • 1
    You probably want to use .hasClass for the test: api.jquery.com/hasclass Commented Jan 30, 2014 at 21:47
  • 1
    Why do you want to add the class min to #hola and then immediately test if it's there? Commented Jan 30, 2014 at 21:52
  • Btw, if you want to toggle between two classes you could use .toggleClass('min max'); Commented Jan 30, 2014 at 23:57

2 Answers 2

1

clase1 is defined prior to the change, and is not a live collection (such as a NodeList) as some reference values in javascript will be. It is just a primitive string.

In order to determine if that class is present, you will need to check again instead of referencing the stored value

var clase1 = $('#hola').attr('class');
$(document).ready(function(){
 $("#hola").click(function(){
  $("#divprincipal").animate({ height:"30px"}, 1000);
  $("#hola").addClass("min");
  clase1 = $('#hola').attr('class');
  alert(clase1);
    if (clase1=="min"){
        $("#divprincipal").animate({ height:"200px"}, 1000);
        $("#hola").addClass("max");
        alert(clase1);
    }
 });
});

Moreover, you may wish to also use jQuery to detect if this class is present instead of looking to see if the whole class name is the same as "min" using hasClass.

if( $('#hola').hasClass('min') )
{
 //conditional code
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to add two classes to same element yo need to do this:

$("#hola").addClass("max min");

1 Comment

Thanks for your fast answer, but that's not was i was looking for. I appreciate your help tho.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.