3.4 其它
:first-child:元素裡的第一個子元素
$("p:first-child")
:找到 p 標籤,然後相對於父元素,如果是第一個子元素的話,就符合。
:last-child:元素裡的最後一個子元素
$("p:last-child")
:找到 p 標籤,然後相對於父元素,如果是最後一個子元素的話,就符合。
:only-child:元素裡只有這個子元素
$("p:only-child")
:找到 p 標籤,然後相對於父元素,如果是只有自己一個元素的話,就符合。例如以下的段落就符合:
<section>
<p>段落(符合)</p>
</section>
:nth-child(n):第幾個子元素
$("p:nth-child(3)")
:p 標籤且是第3個子元素,就符合。
練習
延續 practice/selectors.html
頁面,試以下例子:
$("p:first-child").css("color", "red");
$("p:last-child").css("color", "red");
$("p:only-child").css("color", "red");
$("p:nth-child(3)").css("color", "red");
// 這會加到 body 標籤上了
$(":nth-child(2)").css("color", "red");