jQuery には というセレクターがありfirst-childます。一致した要素から最初の子を選択します。しかしfirst-child、私が使用する代わりにfirst-of-type、それも問題なく動作します。だから私はただ疑問に思っています、違いは何ですか?
$(function(){
//$('li :first-child').text('some text');
$('li :first-of-type').text('some text');
});
ドキュメント(:first-of-typeおよび:first-child)を読むだけです:
:first-child
親の最初の子であるすべての要素を選択します。
:first-of-type
同じ要素名の兄弟の中で最初のすべての要素を選択します。
セレクターは、兄弟のセットの中で、指定された名前 (例: など)の:first-of-type最初の要素と一致します。あなたの例は一致します:spana
<li>
<span>Matches this span</span> <!-- First span amongst siblings -->
<a>Matches this a</span> <!-- First a amongst siblings -->
<a>Doesn't match this one</span> <!-- Second a amongst siblings -->
</li>
:first-childセレクターは、単に親の最初の子に一致します。
<li>
<span>Matches this span</span> <!-- First child of parent -->
<a>Doesn't match this</span> <!-- Second child of parent -->
<a>Nor this</span> <!-- Third child of parent -->
</li>