开发者

if option in select has class then add class

开发者 https://www.devze.com 2023-02-27 18:36 出处:网络
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\">

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</opt开发者_运维技巧ion>
            <option class="2 A" value="2">2</option>
           </select>


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.


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


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:

  • jQuery selectors
  • addClass

...and just generally the jQuery docs.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号