jQuery parent()メソッドで任意の親要素を検索するサンプル

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

構文
var 変数名 = $('セレクタ名’).parent().find('p’);
指定セレクタ名の親要素から子要素の「pタグ」を検索します。
parentメソッドを使って親要素を取得します。

使用例

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(){
var obj = $('.tt').parent().find('p');
console.log(obj[0]);
});
</script>
</head>
<body>
<div>
<p>東京</p>
<p>大阪</p>
<div class="tt">
<span>横浜</span>
</div>
</div>
</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(){ var obj = $('.tt').parent().find('p'); console.log(obj[0]); }); </script> </head> <body> <div> <p>東京</p> <p>大阪</p> <div class="tt"> <span>横浜</span> </div> </div> </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(){  
  var obj = $('.tt').parent().find('p');
  console.log(obj[0]);
});
</script>
</head>
<body>
<div>
    <p>東京</p>
    <p>大阪</p>
    <div class="tt">
        <span>横浜</span>
    </div>
</div>
</body>
</html>

実行結果
1階層上にあるdiv要素「tt」から子要素の「pタグ」を検索します。
コンソールログに下記メッセージを出力します。
<p>東京</p>

jQuery

Posted by arkgame