勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

JavaScript / jQueryで〇番目、最初、最後の要素を指定する方法

  jQuery JavaScript

jQueryでリストタグ(<li>)の〇番目、最初、最後の要素を指定し、何らかの処理を行いたい。また、せっかくなのでJavaScriptでも同じことができるように調べておきたい。以下に対応方法をメモ。

 

対応方法

ソースコード

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function(){
    console.log($(`li`).eq(2).html()); //3
    console.log($(`li:first`).html()); //1
    console.log($(`li:last`).html()); //5
});

console.log(document.querySelector(`ul`).children[2].innerHTML); //3
console.log(document.querySelector(`ul`).firstElementChild.innerHTML); //1
console.log(document.querySelector(`ul`).lastElementChild.innerHTML); //5
</script>

jQueryのeq()やJavaScriptのchildren[]は0番目からカウントする点に注意。

 

リファレンス

.eq()

https://api.jquery.com/eq/

Element: children プロパティ

https://developer.mozilla.org/ja/docs/Web/API/Element/children

Element: firstElementChild プロパティ

https://developer.mozilla.org/ja/docs/Web/API/Element/firstElementChild

Element: lastElementChild プロパティ

https://developer.mozilla.org/ja/docs/Web/API/Element/lastElementChild

 - jQuery JavaScript

  関連記事

Dropzone.jsを使って画像をドラッグ&ドロップでアップロードする方法

画像を複数枚ドラッグ&ドロップでアップロードしたかった。だいぶ前にDro ...

jQueryで配列の値を検索

やりたかった事は、配列の中に特定の値があるか どうか検索し、その後の分岐を行いた ...

AjaxFileUploadで処理は実行できてもエラーが返る

AjaxFileUploadでPHPに通信し、サーバー側のPHPで処理は正常に実 ...

jQuery UIでカレンダーピッカー(Datepicker)の利用方法

フォーム等で日付を入力する際にカレンダーピッカー機能を実装することがある。その際 ...

JavaScript / jQueryにてページ表示時に指定したテキストボックスにフォーカスさせる方法

ページを開いた際に指定したテキストボックス(input type="text") ...