Raj Chaudhuri
Raj Chaudhuri

Reputation: 31

JQuery addClass for CSS subclass

This feels somewhat embarrassing to ask because I feel like I should know the answer. How do you add a CSS subclass to a DIV with JQuery.

So my CSS is =

.class1 .subclass1 {

  width: 10px;
  heigh: 10px;

}

How do I add the subClass1 to a DIV? e.g.

$("#foo").addClass( ????? )

I tried doing addClass( class1 subclass1), but that doesn't work as I believe jquery is expecting subclass1 to be an independent class. Of course, if I get rid of the subclass notion and just call the class "class1-subclass1" in my CSS, then of course it works.

Anyone?

Thanks

Upvotes: 0

Views: 619

Answers (1)

Neom
Neom

Reputation: 107

Let me explain how css class chaining works...

If you write (with a blank space between 2 classes):

.class1 .subclass1{
  width: 10px;
  heigh: 10px;
}

It applies to all "decendents" of a <div id="foo" class="class"> having a class .subclass1 .
For this your html must be formatted something like this:

<div id="foo" class="class1">
  <div class="subclass1">Hello World</div>
</div>

If you want both .class1 and .subclass1 to be applied to the same <div> and you html is something like this:

<div class="class1 subclass1">
  <div class="">Hello World</div>
</div>

Your css must be: (without the blank space between the 2 classes)

.class1.subclass1{
      width: 10px;
      heigh: 10px;
    }

OR....

.class1{
         <some code>
        }
.subclass1{
          width: 10px;
          heigh: 10px;
        }

Now to answer your question:
For JS you are actually adding 2 different classes. Therefore you must call the addClass method twice:

$("#foo").addClass('class');
$("#foo").addClass('subclass');

It's up to you to decide where to the apply the classes.

Upvotes: 1

Related Questions