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
関連記事
-
-
amazon等のECサイトによくにあるアイテムの満足度を星マークで送信・表示する方法
amazon等のECサイトによくにあるアイテムの満足度を星マークかつ5段階で送信 ...
-
-
jQueryで要素を移動する方法のまとめ
jQueryで要素を移動する際、insertBefore / insertAft ...
-
-
jQueryにて指定した要素を検索条件から除外するnot()の利用方法
あるソースコードを拝見しているとjQueryでnot()という使ったことの無いメ ...
-
-
formのpasswordとtextをjQueryで切り替える方法
formでtype="password"を指定していると内容を入力した際に「●● ...
-
-
Javascript / jQueryにて特定の要素内の文字数が〇文字以上の場合に丸める方法
サイトの特定の要素内の文字数が〇文字以上の場合に「コンテンツコンテ……」のように ...