初心者向け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 showとhideで要素を表示と非表示する方法

jQuery showとhideで要素を表示と非表示する方法 jQuery show 要素を表示する方法 showの英語の意味は見せるです。 サンプル $(“セレクタ”).sh …

no image

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

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

no image

jQuery:notセレクタの使い方

jQuery jQuery:notセレクタの使い方 jQuery jQuery:notセレクタの使い方 :notセレクタは条件を指定した以外の要素を指定します。 :not(h2) 使用方法はセレクタに …

no image

jQuery メソッドチェーンとメソッドの種類の使い方

jQuery メソッドチェーンとメソッドの種類の使い方 jQuery メソッドの種類の使い方 メソッドは何らかの処理を実行するためにあります。 $(“セレクタ”).メソッド(パ …

no image

jQuery fadeInとfadeOutフェードインとフェードアウトする方法

jQuery fadeInとfadeOutフェードインとフェードアウトする方法 jQuery fadeInフェードインする方法 フェードインの英語の意味は次第に明るくなる、次第にはっきりするです。 f …