jQuery findで子要素を検索して操作する
環境
jQuery 3.6.4
Windows 10 Home 64bit
構文
$(“.クラス名").find(“.子要素").css(“属性", “値");
findメソッドを使って子要素を検索して操作します。
使用例
「div1」を起点にして、findメソッドでその配下の子要素の「pA」を指定して文字の色を赤にします。
サンプルコード
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnchk").click(function () {
$(".div1").find(".pA").css("color", "red");
});
});
</script>
</head>
<body>
<div class="div1">
<p>tokyo</p>
<p class="pA">oosaa</p>
</div>
<input type="button" id="btnchk" value="テスト" />
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnchk").click(function () {
$(".div1").find(".pA").css("color", "red");
});
});
</script>
</head>
<body>
<div class="div1">
<p>tokyo</p>
<p class="pA">oosaa</p>
</div>
<input type="button" id="btnchk" value="テスト" />
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btnchk").click(function () { $(".div1").find(".pA").css("color", "red"); }); }); </script> </head> <body> <div class="div1"> <p>tokyo</p> <p class="pA">oosaa</p> </div> <input type="button" id="btnchk" value="テスト" /> </body> </html>
実行結果
「テスト」ボタンを押すと、文字「oosaka」の色を赤にします。