jquery prevAllメソッドを使って同一階層のhtml要素から前の全てのhtml要素を取得する

jqueryでprevAllメソッドを使うと「同一階層のhtml要素から前の全てのhtml要素」を取得することができます。ここでは、prevAllメソッドを実際に使用したサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
※windows10にApacheのインストールはこちら
prevAll使い方
ボタンをクリックして、「td」タグのid「test7」の同一階層にある全ての「td」タグのフォントカラーを変更するサンプルコードとなります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> <script src="http://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <style> .container { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> $(function(){ $('.btn').click(function(){ $("#test7").prevAll("td").css("color", "#3eb810"); }); }); </script> <body> <div class="container"> <table class="table"> <thead class="table-striped"> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> <th scope="col">age</th> <th scope="col">email</th> <th scope="col">address</th> </tr> </thead> <tbody> <tr> <th scope="row" id="test1">1</th> <td id="test2">Mark</td> <td id="test3">Otto</td> <td id="test4">@mdo</td> <td id="test5">20</td> <td id="test6">info@mebee.info</td> <td id="test7">japan</td> </tr> </tbody> </table> <button type="button" class="btn btn-raised btn-warning">変換する</button> </div> </body> </html> |
実行結果を見ると、全てのhtmlタグである「td」要素のフォントカラーが変更されることが確認できます。

タグを指定しなければ、全ての要素を取得します。
1 2 3 4 5 |
$(function(){ $('.btn').click(function(){ $("#test7").prevAll().css("color", "#3eb810"); }); }); |
実行結果は以下となります。

-
前の記事
javascript 端数がでないように割り算を行う 2020.08.20
-
次の記事
node.js pm2を使ってプロセスを監視する 2020.08.20
コメントを書く