初心者向けjQuery入門

初心者向けjQuery入門講座です

未分類

jQuery parentとchildren親と子要素を取得する

投稿日:2017年8月22日 更新日:

Query parentとchildren親と子要素を取得する

Query parent 親要素を取得する

parentは指定した要素の親要素を取得します、

サンプル
$(“セレクタ”).parent().メソッド

サンプル

<html>

<head>

<script src=”jquery-3.2.1.js”></script>
<script>

$(function(){
$(“.botton”).click(function(){

$(“.three”).parent().css(“color”,”red”)
});

});

</script>

<title>
</title>

</head>

<body>

<input type=”button” value=”botton” class= “botton” >

<div>

<ul><li>1</li>

<li >2</li>

<li class=”three”>3</li>

<li>4</li>

<li>5</li>

</ul>

</div>

 

</body>

</html>

実行結果は
threeクラスはli要素なのでその親の要素つまりul要素にcssがかかります。
ulの文字色を変えるとul要素と子要素の文字色も適応されるので個別に変えない限り赤になります。
ulのリストのタイトルを空白なので文字色は変わりませんがあればそこも赤色になります。

Query children 子要素を取得する

childrenは指定した要素の子要素を取得します、

サンプル
$(“セレクタ”).children().メソッド

サンプル

<html>

<head>

<script src=”jquery-3.2.1.js”></script>
<script>

$(function(){
$(“.botton”).click(function(){

$(“ul).children().css(“color”,”red”)
});

});

</script>

<title>
</title>

</head>

<body>

<input type=”button” value=”botton” class= “botton” >

<div>

<ul><li>1</li>

<li >2</li>

<li class=”three”>3</li>

<li>4</li>

<li>5</li>

</ul>

</div>

 

</body>

</html>

今回はulをセレクタで指定してその子要素liを取得しました。

全ての子要素のliが赤くなります。

サンプル

<html>

<head>

<script src=”jquery-3.2.1.js”></script>
<script>

$(function(){
$(“.botton”).click(function(){

$(“ul).children(“.three”).css(“color”,”red”)
});

});

</script>

<title>
</title>

</head>

<body>

<input type=”button” value=”botton” class= “botton” >

<div>

<ul><li>1</li>

<li >2</li>

<li class=”three”>3</li>

<li>4</li>

<li>5</li>

</ul>

</div>

 

</body>

</html>

実行結果は
threeクラスだけが赤くなります。

childrenに引数を与えると要素を絞り込めます。

$(“ul”).children(“.three”).css(“color”,”red”)

クラスを指定してるならこの場合はセレクタでクラスを指定したほうが短く書けます。

$(“.threel”).css(“color”,”red”)

 

スポンサードリンク




スポンサードリンク




-未分類
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

jQuery チルダ~の間接セレクタと兄弟セレクタ

jQuery チルダ~の間接セレクタと兄弟セレクタ jQuery チルダ~の間接セレクタと兄弟セレクタ 間接セレクタはチルダを使用します。 兄弟とは親が同じだということですね。 動作は指定した兄弟の以 …

no image

jQuery addclassクラスを追加する方法

jQuery addclassクラスを追加する方法 jQuery addclassクラスを追加する方法 addclassクラスは要素にクラスを設定できます。 どういうことかというこクラスのタブにhtm …

no image

jQuery mouseenterとmouseleaveマウスイベントの方法

jQuery mouseenterとmouseleaveマウスイベントの方法 jQuery mouseenterマウスを乗せた時のイベント方法 mouseenterはマウスを乗せた時に発生するイベント …

no image

jQuery first-childとlast-childの勘違い

jQuery first-childとlast-child jQuery first-child first-childは一番最初の子要素を指定します。 $(“要素:first-child …

no image

jQuery 隣接セレクタと子セレクタのチャイルドセレクタ

jQuery 隣接セレクタと子セレクタのチャイルドセレクタ jQuery 隣接セレクタ 隣接セレクタとは隣に接しているセレクタの二つ目の要素を指定します。 隣り合っているとなっていますが前後にあるセレ …