初心者向け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 first-childとlast-childの勘違い

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

no image

jQuery slideUpとslideDownとslideToggle

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

no image

jQuery prevALLとnextALL前と後の兄弟要素を全て取得する

jQuery prevALLとnextALL前と後の兄弟要素を全て取得する jQuery prevALL前の兄弟要素を全て取得する prevALLメソッドは指定した前の兄弟要素を全て取得します。 サン …

no image

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

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

no image

jQuery 複数のcssのプロパティの設定の方法

jQuery 複数のcssのプロパティの設定の方法 jQuery 複数のcssのプロパティの設定の方法 jQueryでcssを複数設定の方法。 メソッドチェーンで書くとこんな感じになります。 $(&# …