Using jQuery, how to select elements with two CSS classes

Asked

Viewed 18,134 times

10

I have a div that uses two CSS classes. Here is the HTML :

<div class="box1"></div>
<div class="box1 destaque"></div>
<div class="box2"></div>
<div class="box2 destaque"></div>
<div class="box3"></div>

I want to select the div classy box1 and destaque (in my example the second div) only.

What I’ve already tried :

If I do : $('.box1') I select the two Divs with class box1. It’s not what I want.

And if I do : $('.destaque') I just selected a div with box1 and another with box2 (what I don’t want)

I’ve tried to $('.box1 .destaque') but does not select anything.

So how do I mount the jQuery selector to fetch the Divs that use the classes box1 and highlight?

5 answers

16


9

In case it’s just div with .box1 and .destaque:

$('div.box1.destaque');

In the order of selectors, the first can be the desired element, in the example div then you will specify some features of the element:

  • # for ID
  • . class-oriented
  • [] for attributes, example: [rel=teste] selects <div rel="teste">

In the end it is possible to use the : for pseudo selectors (state, as :hover, :active, etc or first child, odd, etc)

When you add the space in the selector, it identifies that you are wanting to go to the next level, so now are child elements of the feature you are seeking.

So $('.box1 .destaque'); will find this:

<div class="box1">
    <div class="destaque"></div> <-- este elemento foi o único selecionado
</div>

<div class="box1 destaque">
    <div></div>
</div>

6

When you say that an element has several properties in both the how much in the you insert all selectors and pseudo classes together

Example:

#id.classe1.classe2[atributo=valor] {
    display: inherit;
}

The above example would correspond to such an element:

<span id="id" class="classe1 classe2" atributo="valor">elemento</span>

If you separate by space you are looking for an element that contains the other. Example:

#id .classe1 .classe2 [atributo='valor'] {
    display: inherit;
}

The above example would correspond to such an element:

<span id="id">
    <span class="classe1">
        <span class="classe2">
            <span atributo="valor">elemento</span>
        </span>
    </span> 
</span>

3

When informing the selector: .box1 .destaque you search for the class .destaque inside .box1. Because the element you want to select has both classes, the correct selector is:.box1.destaque, that would return:

<div class="box1 destaque"></div>

I hope I’ve helped.

1

$(".box2.destaque").html('Class 1');
$(".box1.destaque").html('Class 2');
.box1{
  color: red;
}

.box2{
  color: blue;
}
<div class="box1"></div>
<div class="box1 destaque"></div>
<div class="box2"></div>
<div class="box2 destaque"></div>
<div class="box3"></div>

Browser other questions tagged

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