初心者向け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 セレクタでクラスとIDと要素を指定する方法

jQuery セレクタでクラスとIDと要素を指定する方法 jQuery セレクタ jQueryでは要素にアクセスするにはセレクタを指定しなければいけません。 要素を指定するには$()でセレクタを指定し …

no image

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

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

no image

jQuery removeとemptyの違い

removeとemptyの違い removeとemptyの違い removeとemptyの違い。 removeは要素をDOMから削除します。 emptyは要素を子ノードから削除します。 remove …

no image

jQuery hoverマウスと乗せたり外した時動作するイベント

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

no image

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

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