勉強したことのメモ

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

  関連記事

Jcropを使ってブラウザ上で画像を範囲指定して切り抜き(トリミング)

やりたかった事は、画像をアップロードして必要な部分のみを範囲指定してもらい、指定 ...

日付の範囲指定用プラグイン「DateRangePicker」の利用方法

日付型のデータを検索する際に開始・終了日のテキストボックスを用意し、それぞれにタ ...

jQuery.uploadでリアルタイムプレビュー

やりたい事は、 ・<input type="file">で画像を選択 ...

jQueryとCSSで指定したテキストに対してラインマーカーを引く方法

サイト内で強調したいテキストに対して蛍光ペンでマーカーを引くようなアニメーション ...

日本地図のクリッカブルマップをjQueryで実装する方法(japan-map)

JavaScriptもしくはjQueryで日本地図を表示し、都道府県や八地方区分 ...