jQueryで複数セレクタを and 条件と or 条件で指定するときの指定方法の違いをメモする

はまったのでメモ。
jQueryセレクタを複数条件で指定したい場合などがある。


例えばこんな場合

<table>
   <tr>
      <td class="a" id="1">a-1</td>
      <td class="a" id="2">a-2</td>
      <td class="a" id="3">a-3</td>
   </tr>
   <tr>
      <td class="b" id="4">b-4</td>
      <td class="b" id="5">b-5</td>
      <td class="b" id="6">b-6</td>
   </tr>
</table>

こんなテーブル構造があった場合。

classが"a"、idが"5"のカラムの色を変えたい場合。
    $(function() {
        $(".a,#5").css("backgroundColor", "red");
    });

これでOK。
これは or 条件ですね。

classが"b"で、かつidが"4"のカラムの色を変えたい場合。
    $(function() {
        $(".b" + "#4").css("backgroundColor", "red");
    });

こうします。


つまり、
or条件なら

セレクタ1, セレクタ2

and条件なら

セレクタ1 + セレクタ2

とします。

応用編 (classが"a"で、かつidが"2"のカラムと、class="b"で、かつidが"4"と"6"のカラム)
    $(function() {
        $(".a" + "#2" + "," + ".b" + "#4,#6").css("backgroundColor", "red");
    });


勉強になりましたm(_ _)m