jQuery filterメソッドで要素を絞り込んで処理を行うサンプル

環境
Google Chrome 111.0.5563.65(Official Build)
Windows 10 Home 64bit
jquery 3.6.3

書式
$(“.クラス名).filter(function(){処理コード})
jQueryのfilterメソッドです。
要素を絞り込んで処理を行います。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnshow").click(function(){
const nm=25;
/*filterメソッド*/
$(".num").filter(function(){
/*関数で要素をフィルタリング*/
return $(this).val() <nm;
}).css("background","Skyblue");
});
});
</script>
</head>
<body>
<input type="text" class="num" value="11" maxlength="2"><br>
<input type="text" class="num" value="22" maxlength="2"><br>
<input type="text" class="num" value="33" maxlength="2"><br>
<input type="text" class="num" value="44" maxlength="2"><br>
<input type="text" class="num" value="55" maxlength="2"><br>
<input type="button" id="btnshow" value="表示" />
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btnshow").click(function(){ const nm=25; /*filterメソッド*/ $(".num").filter(function(){ /*関数で要素をフィルタリング*/ return $(this).val() <nm; }).css("background","Skyblue"); }); }); </script> </head> <body> <input type="text" class="num" value="11" maxlength="2"><br> <input type="text" class="num" value="22" maxlength="2"><br> <input type="text" class="num" value="33" maxlength="2"><br> <input type="text" class="num" value="44" maxlength="2"><br> <input type="text" class="num" value="55" maxlength="2"><br> <input type="button" id="btnshow" value="表示" /> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btnshow").click(function(){
      const nm=25;
      /*filterメソッド*/
       $(".num").filter(function(){
         /*関数で要素をフィルタリング*/
          return $(this).val() <nm;
       }).css("background","Skyblue");
    });


});
</script>
</head>
<body>

<input type="text" class="num" value="11" maxlength="2"><br>
<input type="text" class="num" value="22" maxlength="2"><br>
<input type="text" class="num" value="33" maxlength="2"><br>
<input type="text" class="num" value="44" maxlength="2"><br>
<input type="text" class="num" value="55" maxlength="2"><br>
<input type="button" id="btnshow" value="表示" />

</body>
</html>

実行結果
「表示」ボタンを押すと25より小さい値のテキストボックスの色(SkyBlue)が変わります。

jQuery

Posted by arkgame