jQuery findで引数に属性セレクタを指定する方法
環境
Google Chrome 111.0.5563.65(Official Build)
Windows 10 Home 64bit
jquery 3.6.3
書式
$(“.クラス名").find(“input[type=’text’]").attr(属性名 値);
findメソッドを使用して引数に属性セレクタを指定します。
inputの範囲を括るダブルコーテション(“)とtextの範囲を括るシングルコーテーション(')です。
ダブルコーテションとシングルコーテーションの位置を逆にしても動作します。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnchk").click(function(){
$(".cft").find("input[type='text']").attr("name","city");
});
});
</script>
</head>
<body>
<div class="cft">
<input type="text" value="東京" />
</div><br>
<input type="button" id="btnchk" value="テスト" />
</body>
</html>
実行結果
「テスト」ボタンを押すと、div要素「cft」を起点にして、
findメソッドで子要素のinputのtypeがtextの要素を指定し、
attrメソッドでnameとnameの値を追加しています。