jquery lengthメソッドを利用しているクラスの数をカウントする

jqueryでlengthメソッドを使ってページ上で使用しているクラスの数をカウントするサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- jquery 3.5.1
※windows10にApacheのインストールはこちら
lengthメソッド利用
下記のコードで簡単に取得することができます。
1 |
var count = $(".クラス名").length; |
クラス名「btn」をカウントするサンプルコードとなってます。
※CSSは「 bootstrap-material 」を使用してます。
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 61 62 |
<!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> .app { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; width: 500px; } </style> <script> $(document).ready(function(){ //btnクラスをカウントする $("#btn").click(function(){ var count = $(".btn").length; $('.alert-primary').text(count); }); }); </script> <body> <div class="app"> <div id="txt" class="alert alert-primary" role="alert"> </div> <div> <button type="button" class="btn btn-primary bmd-btn-fab"> <i class="material-icons">grade</i> </button> <button type="button" class="btn btn-secondary bmd-btn-fab"> <i class="material-icons">grade</i> </button> <button type="button" class="btn btn-success bmd-btn-fab"> <i class="material-icons">grade</i> </button> <button type="button" class="btn btn-info bmd-btn-fab"> <i class="material-icons">grade</i> </button> <button type="button" class="btn btn-warning bmd-btn-fab"> <i class="material-icons">grade</i> </button> <button type="button" class="btn btn-danger bmd-btn-fab"> <i class="material-icons">grade</i> </button> <button type="button" class="btn btn-danger bmd-btn-fab active"> <i class="material-icons">grade</i> </button> </div> <button id="btn" type="button" class="btn btn-raised btn-warning">count</button> </div> </body> </html> |
8と表示され、正確にカウントされているが確認できます。

-
前の記事
spring initializrを利用してeclipseにspring bootプロジェクトを構築する 2020.08.09
-
次の記事
windows10 nginxをインストールして使用する 2020.08.09
コメントを書く