LoginSignup
5
5

More than 5 years have passed since last update.

テキストに応じて条件を分岐する

Posted at

テーブルでセルのテキストに応じて、親trの背景色を変えたいと思ったときにちょっとハマったので、メモ。

良くない例

これではうまくいきませんでした。

$(function(){
    $('table td').each(function(){
        if($(this).text() === 'hoge'){
            $(this).parents('tr').addClass('hoge');
        }else {
            $(this).parents('tr').addClass('huge');
        }
    });
});

どうしていけなかったのか?

文字は、"合っているか"ではなく、”含まれているか”で判定してやらないといけなかった。
$(this).text() === 'hoge'$(this).text().indexOf('hoge') != -1

こうしたらうまくいった。

$(function(){
    $('table td').each(function(){
        if($(this).text().indexOf('hoge') != -1){
            $(this).parents('tr').addClass('hoge');
        }else {
            $(this).parents('tr').addClass('huge');
        }
    });
});
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5