初心者向け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 eq要素のインデックスを取得する

jQuery eq要素のインデックスを取得する jQuery eq要素のインデックスを取得する eqは指定した要素のインデックスを指定する。 サンプル $(“セレクタ”).eq …

no image

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

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

no image

jQuery widthとheight要素の横と縦を設定する

jQuery widthとheight要素の横と縦を設定する jQuery width 要素のサイズの横幅を設定するにはwidthメソッドを使用します。 $(“セレクタ”).w …

no image

jQuery clickクリックイベントの書き方

clickクリックイベントの書き方 clickクリックイベントの書き方 クリックイベントの書き方の前にイベントの書き方を解説します。 サンプル $(function(){ $(“セレクタ& …

no image

jQuery slideUpとslideDownとslideToggle

jQuery slideUpとslideDownとslideToggle jQuery slideUp slideUpはスライドをアップします。 要素が上に上がっていき非表示になります。 サンプル $ …