Kodekan
Kodekan

Reputation: 1601

jQuery select elements of one class within another class

I have elements with the class "some_class" inside various divs that have individual classes/ids, like in this example:

<div class="alpha">
    <p class="some_class">Text</p>
    <p class="some_class">More text</p>
</div>
<div class="beta">
    <p class="some_class">Even more text</p>
    <p class="some_class">Bored now</p>
</div>

I can use jQuery to select all elements with the class "some_class" and toggle another class like this:

$('.toggle_button').click(function () {
    $('.some_class').toggleClass('another_class');
    //do more stuff
});

How would I write a function that toggles only those elements of "some_class" that are within the "alpha"/"beta" divs?

Upvotes: 0

Views: 2617

Answers (3)

Venkata Krishna
Venkata Krishna

Reputation: 15112

$('.alpha,.beta').find('.some_class').toggleClass('another_class');

JSFIDDLE DEMO

Upvotes: 1

Use .children() , .find()

$('.alpha').children('.some_class').toggleClass('another_class');


Child Selector

$('.alpha > .some_class').toggleClass('another_class')

$('.alpha .some_class').toggleClass('another_class');


Multiple Selector

$('.alpha .some_class,.beta .some_class').toggleClass('another_class');


$('.alpha,.beta').find('.some_class').toggleClass('another_class');

Upvotes: 1

j08691
j08691

Reputation: 208003

$('.alpha .some_class, .beta .some_class').toggleClass('another_class');

Upvotes: 1

Related Questions