jqueryセレクターの取得方法まとめです。
事前準備
以下のhtmlを使用して説明します
HTMLファイル
<body>
<div class="block sec1">
<h1>見出し(h1タグ)</h1>
<p>中身1(pタグ)</p>
<p>中身2(pタグ)</p>
<p>中身3(pタグ)</p>
</div>
<div class="block sec2">
<p>中身4(pタグ)</p>
<p>中身5(pタグ)</p>
<p>中身6(pタグ)</p>
<div>補足(divタグ)</div>
</div>
<div class="block sec3">
<p>中身7(pタグ)</p>
<p>中身8(pタグ)</p>
<p>中身9(pタグ)</p>
</div>
</body>
実行結果
番号を指定して取得する
0が数える基準となります。0=1番目、1=2番目・・・・
eq(equal) 等しい
$("p:eq(2)");
p要素の3番目を取得
「中身3」
gt(greater than) より大きい
$("p:gt(2)");
p要素の3番目より大きい要素を全て取得
「中身3」から「中身9」
lt(less than) より小さい
$("p:lt(2)");
p要素の3番目より小さい要素を全て取得
「中身1」「中身2」
even 偶数
$("p:even");
p要素の偶数番号を取得
「中身1」「中身3」「中身5」「中身7」「中身9」
odd 奇数
$("p:odd");
p要素の奇数番号を取得
「中身2」「中身4」「中身6」「中身8」
先頭を取得する(first)
first
$("p:first");
p要素の最初の1つを取得
「中身1」
first-child
$("p:first-child");
親が同一で最初のp要素を厳密に全て取得
「中身4」と「中身7」
「中身1」は<div class="block sec1">の最初(0番目)が
divタグ(pタグではない)のため取得されない
first-of-type
$("p:first-of-type");
親が同一の最初のp要素を全て取得
「中身1」「中身4」「中身7」
最後を取得する(last)
last
$("p:last");
p要素の最後の1つを取得
「中身9」
last-child
$("p:last-child");
親が同一で最後のp要素を厳密に全て取得
「中身3」と「中身9」
「中身6」は<div class="block sec2">の最後が
divタグ(pタグではない)のため取得されない
last-of-type
$("p:last-of-type");
親が同一で最後のp要素を全て取得
「中身3」「中身6」「中身9」
n番目を取得する(nth)
nthはCSS由来のため1番目は(1)になります
nth-child()
$("p:nth-child(2)");
親が同一で2番目のp要素を厳密に全て取得
「中身1」「中身5」「中身8」
中身1が取れる理由は<div class="block sec1">では
最初のh1タグが1番目とカウントされるため
()内では偶数奇数判定や数式も使用可能です
even 偶数番目
odd 奇数番目
3n+1 3の倍数+1
nth-of-type()
$("p:nth-of-type(2)");
親が同一で2番目のp要素を全て取得
「中身2」「中身5」「中身8」
nth-last-child()
$("p:nth-last-child(2)");
親が同一で最後から2番目のp要素を厳密に全て取得
「中身2」「中身6」「中身8」
中身6が取れる理由は<div class="block sec2">では
最後にdivタグ(補足)があるため1番目としてカウントされている
nth-of-type()
$("p:nth-of-type(2)");
親が同一で2番目のp要素を全て取得
「中身2」「中身5」「中身8」
後を取得する(+/~)
+
$(".sec1 + div");
クラス.sec1の直後のdivを取得
<div class="block sec2">全体
~
$(".sec1 ~ div");
クラス.sec1以降のdivを全て取得
<div class="block sec2">全体
<div class="block sec3">全体
子孫や子の取得
半角スペース開け
$("body div")
body内全てのdiv要素を取得する(子孫)
<div class="block sec1">全体
<div class="block sec2">全体
<div>補足(divタグ)
<div class="block sec3">全体
>
$("body > div")
body内直下全てのdiv要素を取得する(子)
<div class="block sec1">全体
<div class="block sec2">全体
<div class="block sec3">全体