初心者向け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 子孫セレクタ 子孫セレクタとは 要素には親要素と子要素があります。 ulだと子はliですね。 それとdivの中にp要素を入れ子にし …

no image

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

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

no image

jQuery first-childとlast-childの勘違い

jQuery first-childとlast-child jQuery first-child first-childは一番最初の子要素を指定します。 $(“要素:first-child …

no image

jQuery メソッドチェーンとメソッドの種類の使い方

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

no image

jQuery prevとnext前と後の要素取得する

jQuery prevとnext前と後の要素取得する jQuery prev前の要素取得する prevは英語の略語で previous(以前の) 等です。 prevは指定した要素の前の要素を取得します …