jQuery eachメソッドを使ってDOM要素を繰り返し処理するサンプル
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1
構文
$(要素).each(function (インデックス, 要素) {
// 繰り返す処理コード
});
DOM要素(タグ)に対して処理を繰り返します。
functionの1つめの引数はインデックスです。
functionの2つめの引数は要素です。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// each処理を繰り返す
$("td").each(function(index,val){
console.log(index +":"+$(val).text());
});
});
</script>
</head>
<body>
<table border="1" width="80%">
<tr>
<td>東京</td>
<td>大阪</td>
<td>福岡</td>
</tr>
</table>
</body>
</html>
実行結果
0:東京
1:大阪
2:福岡