Frank Conway
Frank Conway

Reputation: 23

Filter one div with same class as others with jQuery

Here is a fiddle.
As you can see when a colour from the select drop down is selected all the divs with the class ".box" change colour.
Is it possible to only change one div at a time, leaving the others as they are? There will be hundreds of these so changing the class/id of each one is not really an option.
I have tried a bunch of filters with no luck.

Upvotes: 0

Views: 272

Answers (3)

Arash Milani
Arash Milani

Reputation: 6308

change your js code to this:

$('select').change(function(){
    $(this).siblings('.box').removeClass('red green blue').addClass(
        $(this).find('option:selected').text().toLowerCase()
    );
})
.change();

Upvotes: 1

Wouter J
Wouter J

Reputation: 41934

Use .prev( selector ), in your example it would be:

$('select').change(function() {
  $(this).prev('.box').addClass();
});

Live example: http://jsfiddle.net/nFGRa/2/

Upvotes: 0

xdazz
xdazz

Reputation: 160863

You could provide a context for $('.box'), which is $(this).parent().

$('select').change(function(){
    $('.box', $(this).parent()).removeClass('red green blue').addClass(
        $(this).find('option:selected').text().toLowerCase()
    );
})
.change();

Upvotes: 2

Related Questions