LoginSignup
13
6

More than 5 years have passed since last update.

jQueryのセレクタ:firstと:first-childの違い

Posted at

知らなかったのでメモ
(:last,:last-childも同じ)

$('ul li:first')
すべてのulタグ内をあわせたliタグの中の最初の要素を選択

$('ul li:first-child')
各ulタグ内にあるそれぞれのliタグの最初の要素を選択

つまり

$('ul li:first').css('color','red');

<ul>
  <li>リスト1</li> //ここだけ赤
  <li>リスト2</li>
  <li>リスト3</li>
</ul>
<ul>
  <li>リスト1</li>
  <li>リスト2</li>
  <li>リスト3</li>
</ul>
<ul>
  <li>リスト1</li>
  <li>リスト2</li>
  <li>リスト3</li>
</ul>

$('ul li:first-child').css('color','red');

<ul>
  <li>リスト1</li> //赤
  <li>リスト2</li>
  <li>リスト3</li>
</ul>
<ul>
  <li>リスト1</li> //赤
  <li>リスト2</li>
  <li>リスト3</li>
</ul>
<ul>
  <li>リスト1</li> //赤
  <li>リスト2</li>
  <li>リスト3</li>
</ul>
13
6
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
13
6