初心者向け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 wrapとunwrap親要素を追加と削除

jQuery wrapとunwrap親要素を追加と削除 jQuery wrap 親要素を追加 wrapは親要素を追加します サンプル $(“セレクタ”).wrap(&#8216 …

no image

jQuery prependとappendの違いと要素の追加

jQuery prependとappendの違いと要素の追加 jQuery prependとappendの違い prependとappendの違いはprependは指定した要素の要素の先頭に追加されま …

no image

jQuery セレクタでクラスとIDと要素を指定する方法

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

no image

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

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

no image

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

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