初心者向けjQuery入門

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

未分類

jQuery firstとlast最初と最後の要素を取得する

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

jQuery firstとlast最初と最後の要素を取得する

jQuery first最初の要素を取得する

firstメソッドは最初の要素を取得します。
サンプル

$(“セレクタ”).first().メソッド

サンプル

<html>

<head>

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

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

$(“li”).first().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>

実行結果は最初の要素1が赤くなります。

このコードはセレクタで書き換えることができます。

$(“li:first-child”).css(“color”,”red”)

どちらを使うかは自由です。

jQuery last最後の要素を取得する。

lastメソッドは最後の要素を取得します。
サンプル
サンプル

<html>

<head>

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

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

$(“li”).last().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>

実行結果は最後の要素5が赤くなります。

このコードはセレクタで書き換えることができます。

$(“li:last-child”).css(“color”,”red”)

どちらを使うかは自由です。

スポンサードリンク




スポンサードリンク




-未分類
-

執筆者:


comment

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

関連記事

no image

jQuery showとhideで要素を表示と非表示する方法

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

no image

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

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

no image

jQuery nth-child偶数と奇数と二番目指定する方法

jQuery nth-child偶数と奇数nth-last-childとnth first child jQuery nth-child nth-childは何番目の要素を指定するセレクタです。 nt …

no image

jQuery beforeとafterの違いと要素の追加

jQuery beforeとafterの違いと要素の追加 jQuery beforeとafterの違い beforeとafterは基本的な動作は似てます。 共通してるのは要素を追加することです。 違う …

no image

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

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