[jQuery]findメソッドで子要素を検索して操作するサンプル

環境
Windows 11 Pro 64bit
jquery 3.6.0

構文
要素.find( selector/要素 )
$(セレクタ名).find(子要素のタグ名).css(属性,値);
findメソッドは、指定の要素から子孫要素を検索します。
指定の要素を起点に子要素を検索し一致した子要素の属性を値にします。

使用例

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.0/jquery.min.js"></script>
<script>
$(function () {
$("#btnchk").click(function() {
// 子要素pAの背景色を変更
$(".cft").find(".pA ").css("color","red");
});
});
</script>
</head>
<body>
<input type="button" id="btnchk" value="検証">
<div class = "cft">
  <!--子要素pA -->
<p class="pA">fukuoka
<span class="uu">テスト</span></p>
<p class="pB">tokyo</p>
</div>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function () { $("#btnchk").click(function() { // 子要素pAの背景色を変更 $(".cft").find(".pA ").css("color","red"); }); }); </script> </head> <body> <input type="button" id="btnchk" value="検証"> <div class = "cft">   <!--子要素pA --> <p class="pA">fukuoka <span class="uu">テスト</span></p> <p class="pB">tokyo</p> </div> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
 $(function () {
      $("#btnchk").click(function() {
       // 子要素pAの背景色を変更
            $(".cft").find(".pA ").css("color","red");
      });
     });
</script>
</head>
<body>
<input type="button" id="btnchk" value="検証">
<div class = "cft">
  <!--子要素pA -->
      <p class="pA">fukuoka
            <span class="uu">テスト</span></p>
     <p class="pB">tokyo</p>
</div>
</body>
</html>

実行結果
「検証」ボタンを押すと、findメソッドで子要素の「pA」を指定して文字の色を赤にします。

jQuery

Posted by arkgame