初心者向け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 hoverマウスと乗せたり外した時動作するイベント

jQuery hoverマウスと乗せたり外した時動作するイベント jQuery hoverマウスと乗せたり外した時動作するイベント hoverはマウスを乗せたり外したりしたときに起動するイベントです。 …

no image

jQuery removeClassクラスを削除する方法

jQuery removeClassクラスを削除する方法 jQuery removeClassクラスを削除する方法 htmlで設定したクラスを削除します。 cssで設定したクラスでも削除はできます。 …

no image

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

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

no image

jQuery attrとremoveAttr属性の取得と設定と削除

jQuery attrとremoveAttr属性の取得と設定と削除 attrはattributeの略ですね。 英語で属性という意味です。 jQuery attr属性の設定する サンプル $(&#822 …

no image

jQuery animate要素をアニメーションさせる

jQuery animate要素をアニメーションさせる jQuery animate要素をアニメーションさせる animateの英語の意味は 生命を吹き込む,活気づける、活発にする、励ます、動画にする …