「jQuery」parentとchildrenメソッドで親と子の要素に移動するサンプル
環境
jQuery 3.6.0
Google Chrome 105.0.5195.127
Windows 10 home 64bit
構文
1.親の要素の移動
$(セレクター名).parent()
parentを使って親に移動します。
2.子要素の移動
$(セレクター名).children()
childrenを使用して、子要素に移動します。
使用例
<!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(){
//親要素
const cftA = $("#pA").parent(); // 親要素に移動
cftA.css("color", "skyblue"); // 行の文字が緑になる※
//子要素
const d2 = $("#pB").children(); // 子要素に移動
d2.css("color", "red"); // 文字が黄色になる
});
});
</script>
</head>
<body>
<div id="pA">AA
<div id="pB">BB
<div id="pC1">CC 33</div>
<div id="pC2">CC 44</div>
</div>
</div>
<input type="button" id="btnchk" value="検証" />
</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(){
//親要素
const cftA = $("#pA").parent(); // 親要素に移動
cftA.css("color", "skyblue"); // 行の文字が緑になる※
//子要素
const d2 = $("#pB").children(); // 子要素に移動
d2.css("color", "red"); // 文字が黄色になる
});
});
</script>
</head>
<body>
<div id="pA">AA
<div id="pB">BB
<div id="pC1">CC 33</div>
<div id="pC2">CC 44</div>
</div>
</div>
<input type="button" id="btnchk" value="検証" />
</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(){ //親要素 const cftA = $("#pA").parent(); // 親要素に移動 cftA.css("color", "skyblue"); // 行の文字が緑になる※ //子要素 const d2 = $("#pB").children(); // 子要素に移動 d2.css("color", "red"); // 文字が黄色になる }); }); </script> </head> <body> <div id="pA">AA <div id="pB">BB <div id="pC1">CC 33</div> <div id="pC2">CC 44</div> </div> </div> <input type="button" id="btnchk" value="検証" /> </body> </html>
実行結果
「検証」ボタンを押すと、1と2行のテキストの文字が「skyblue」になります。
3と4行のテキストの文字が「red」になります。