「jQuery」findメソッドで子要素を検索して操作するサンプル
環境
Google Chrome 103.0.5060.114 Windows 10 Home 64bit jQuery 3.6.0
構文
$(要素.find(“.クラス名").css(属性, 値);
jQueryのfindメソッドは、指定の要素から子孫要素を検索します。
指定の要素を起点に子要素を検索し一致した子要素の属性の値を追加します。
使用例
<!DOCTYPE html>
<html>
<body>
<div class="cft">
<p>tokyo</p>
<p class="cft">oosaka</p>
</div>
<input type="button" id="btnset" value="設定" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$("#btnset").click(function () {
//子要素を検索して操作する
$(".cft").find(".city").css("color", "blue");
});
</script>
</body>
</html>
実行結果
div要素「cft」を起点にして、findメソッドでその配下の子要素の「city」を指定して文字の色を青にします。