jQuery parentsメソッドで先祖要素の取得方法
環境
jquery 3.6.3
Google Chrome 110.0.5481.104(Official Build) (64 ビット)
構文
1.parentsメソッドを使って先祖要素でセレクタにマッチする要素をすべて取得します。
$(“#セレクターID名").parents().css(処理);
2.ボタンイベントの定義
$(“button").click(function(){処理コード
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#tokyo").parents().css("color","blue");
});
});
</script>
</head>
<body>
<button id="tt">テスト</button>
<ul id="city">
<ul id="cityname">
<li id="tokyo">東京</li>
<li id="oosaka">大阪</li>
</ul>
</ul>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#tokyo").parents().css("color","blue");
});
});
</script>
</head>
<body>
<button id="tt">テスト</button>
<ul id="city">
<ul id="cityname">
<li id="tokyo">東京</li>
<li id="oosaka">大阪</li>
</ul>
</ul>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#tokyo").parents().css("color","blue"); }); }); </script> </head> <body> <button id="tt">テスト</button> <ul id="city"> <ul id="cityname"> <li id="tokyo">東京</li> <li id="oosaka">大阪</li> </ul> </ul> </body> </html>
実行結果
「テスト」ボタンを押すと、「tokyo」をセレクタに指定し、parents要素で
文字色を青に変えます。「tokyo」および「oosaka」の文字色を青に変えます。