user472285
user472285

Reputation: 2674

if option in select has class then add class

is there a way to do: if options have class 1 and 2 then add class A in jQuery?

So this :

<select class="rubrique" name="ctl00">
            <option class="" value="" selected="selected"></option>
            <option class="1" value="1">1</option>
            <option class="2" value="2">2</option>
           </select>

would give me that:

 <select class="rubrique" name="ctl00">
            <option class="" value="" selected="selected"></option>
            <option class="1 A" value="1">1</option>
            <option class="2 A" value="2">2</option>
           </select>

Upvotes: 0

Views: 5267

Answers (4)

David Thomas
David Thomas

Reputation: 253308

If you want both class 1 and class 2 to be present:

$('.rubrique > .1.2').addClass('A');

You can chain the class-selector . and class-names to find elements with both.

Otherwise, as noted, if you want to add class A to both:

$('.rubrique > .1, .rubrique > .2').addClass('A');

Is what's needed.

With thanks @T.J. Crowder for pointing out my original mis-reading of the question example.

Upvotes: 1

Sarah West
Sarah West

Reputation: 2037

jQuery("option").each(function(){
   if(jQuery(this).hasClass("1") && jQuery(this).hasClass("2")) {
      jQuery(this).addClass("A");
   }
});

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074028

I'd've thought the answers to your other question would've shown you how to get there pretty easily.

Basically, you just change the selector a bit, and since your class no longer varies based on the element, you don't need to use a function, just a string:

$('.rubrique option.1, .rubrique option.2').addClass("A");

...but note that "1" and "2" are invalid CSS class names.

Further reading:

...and just generally the jQuery docs.

Upvotes: 1

CoolEsh
CoolEsh

Reputation: 3154

$( '.rubrique > option.1, .rubrique > option.2' ).addClass( 'A' );

Upvotes: 1

Related Questions