「jQuery」eachメソッドでhtml要素に対して繰り返す処理サンプル

環境
Google Chrome 104.0.5112.81
jQuery 3.6.0

構文

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$('オブジェクト').each(function(index, element){
//繰り返し実行する処理コード 
alert(index + ':' + $(element).text());
})
$('オブジェクト').each(function(index, element){ //繰り返し実行する処理コード  alert(index + ':' + $(element).text()); })
$('オブジェクト').each(function(index, element){
      //繰り返し実行する処理コード 
        alert(index + ':' + $(element).text());
})

each() メソッドの引数にはコールバック関数を指定します。
コールバック関数の第1引数を指定することによって、index を取得します。
$(element).text()
jqueryオブジェクトのテキスト内容を取得します。

使用例

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.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#show").click(function(){
  $('li').each(function(index, element){
 alert(index + ':' + $(element).text());
 })
 });
});
</script>
</head>
<body>
<ul>
<li>東京</li>
<li>大阪</li>
<li>福岡</li>
</ul>
<button id="show">表示</button>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ $("#show").click(function(){   $('li').each(function(index, element){  alert(index + ':' + $(element).text());  })  }); }); </script> </head> <body> <ul> <li>東京</li> <li>大阪</li> <li>福岡</li> </ul> <button id="show">表示</button> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $("#show").click(function(){
     $('li').each(function(index, element){
       alert(index + ':' + $(element).text());
      })
     });
  });
</script>
</head>
<body>
<ul>
  <li>東京</li>
  <li>大阪</li>
  <li>福岡</li>
</ul>
<button id="show">表示</button>
</body>
</html>

結果
「表示」ボタンを押下すると、「0:東京」、「1:大阪」と「2:福岡」というメッセージが表示されます。

jQuery

Posted by arkgame