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
関連記事
-
-
jQueryにて$.parseHTML()を用いてHTML文字列をDOMノードに変換する方法
あるサイトのソースコードを拝見しているとjQueryで$.parseHTML() ...
-
-
jQuery UIのDatepickerでリセット(入力内容消去)ボタンの追加方法
jQuery UIのDatepickerでキーボード入力を防ぎたいためreado ...
-
-
IE11でフォーム送信時に二重登録される
Internet Explorer11でform送信時にデータが二重登録されると ...
-
-
FlashとjQueryを組み合わせたプラグインでWebカメラで撮影した画像をアップロード
FlashとjQueryを組み合わせたプラグインを用いてWebカメラで撮影した画 ...
-
-
FullCalendarでカレンダー内のイベントをクリックした際にタイトル以外の内容も表示させる方法
FullCalendarでカレンダー内のイベントをクリックした際にtitle以外 ...