jQuery eachとfindメソッドで複数の要素を操作するサンプル

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1

構文
$('.セレクター名’).find(“input[type=’text’]").each(function() {処理コード
findメソッドで子要素のinputのtypeがtextの要素を指定しています。
$(this).attr(属性名,値)
attrメソッドを使って指定属性名と属性名の値を追加しています。

使用例

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.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnchk").click(function() {
// findメソッドで子要素のinputのtypeがtextの要素を指定
$('.city').find("input[type='text']").each(function() {
// attrメソッドでnameとnameの値を追加
$(this).attr("name","city")
})
});
});
</script>
</head>
<body>
<div class = "city">
<input type="text" value="tokyo"><br>
<input type="text" value="oosaka"><br>
<input type="text" value="fukuoka">
</div>
<p><input type="button" id="btnchk" value="確認"></p>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btnchk").click(function() { // findメソッドで子要素のinputのtypeがtextの要素を指定 $('.city').find("input[type='text']").each(function() { // attrメソッドでnameとnameの値を追加 $(this).attr("name","city") }) }); }); </script> </head> <body> <div class = "city"> <input type="text" value="tokyo"><br> <input type="text" value="oosaka"><br> <input type="text" value="fukuoka"> </div> <p><input type="button" id="btnchk" value="確認"></p> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
      $("#btnchk").click(function() {
    // findメソッドで子要素のinputのtypeがtextの要素を指定
            $('.city').find("input[type='text']").each(function() {
        // attrメソッドでnameとnameの値を追加
                  $(this).attr("name","city")
            })
      });
    });
</script>
</head>
<body>
<div class = "city">
      <input type="text" value="tokyo"><br>
      <input type="text" value="oosaka"><br>
      <input type="text" value="fukuoka">
</div>
<p><input type="button" id="btnchk" value="確認"></p>
</body>
</html>

実行結果
<input type="text" value="tokyo" name="city">
<input type="text" value="oosaka" name="city">
<input type="text" value="fukuoka" name="city">

jQuery

Posted by arkgame