0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jQuery セレクターの取得方法まとめ(位置で取得)

Last updated at Posted at 2020-07-15

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>

実行結果

※1部CSSで色付けしています
Image from Gyazo

番号を指定して取得する

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">全体

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?