初心者向け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 メソッドチェーンとメソッドの種類の使い方

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

no image

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

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

no image

jQuery mouseoverとmouseoutマウスイベントの方法

Query mouseoverとmouseoutマウスイベントの方法 Query mouseoverマウスを乗せた時のイベントの方法 mouseoverはマウスを要素に乗せた時に発生するイベントです。 …

no image

jQuery textメソッドとhtmlの違い 文字列を変更する

jQuery textメソッド 文字列を変更する jQuery textメソッド 文字列を変更する textメソッドは要素のtextを変更することができます。 $(“セレクタ” …

no image

jQuery slideUpとslideDownとslideToggle

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