JavaScript / jQueryで〇番目、最初、最後の要素を指定する方法
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()
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
関連記事
-
-
formでGET送信時に空のパラメータを送信しない方法(cleanQuery)
フォームでGET送信する際、通常だと空のパラメータも送信される。結果として「ドメ ...
-
-
YouTubeの埋め込み動画をjQuery&CSSでフローティングビデオ対応させる方法
以前にvideoタグで表示させた動画をjQuery&CSSでフローティン ...
-
-
jQueryのfind実行時に複数のセレクタを指定する方法
jQueryのfind()実行時に複数のセレクタを指定したい。 <div ...
-
-
画像アップロード前の時点で画像が選択されているか確認
やりたかった事は、フォーム内で画像をアップロードする際、 ちゃんと画像がローカル ...
-
-
Flashを用いずJavaScriptでコピー&カット機能を実装する方法
以前メモったようなFlashを用いる方法ではなく、WebAPIでコピー& ...