I'm really not getting the idea of :first-child
and :last:child
clear. Can you just show an exampl开发者_StackOverflowe that clarifies those two filters?
Demo
1. HTML
<ul>
<li>First</li>
<li>Child</li>
<li>Child</li>
<li>Child</li>
<li>Last</li>
</ul>
2. CSS
.red{
color: red;
}
.blue{
color: blue
}
3. jQuery
$('ul :first-child').addClass('red');
$('ul :last-child').addClass('blue');
In this case, a css class red
would be added to the first li
element, whereas a css class blue
would be added to the last li
element.
<ul>
<li>
<a><img src="mysource" alt="my alt tag 1"/></a>
</li>
<li>
<a><img src="mysource" alt="my alt tag 2"/></a>
</li>
<li>
<a><img src="mysource" alt="my alt tag 3"/></a>
</li>
<li>
<a><img src="mysource" alt="my alt tag 4"/></a>
</li>
</ul>
$("ul li:last-child)
will give you the last one :
<li>
<a><img src="mysource" alt="my alt tag 4"/></a>
</li>
it scans to get the last child in a spscific range .
same goes for the first child
http://jsfiddle.net/mMYrf/6/
If you have alot of elements you can directly chose the last and first of them, no matter how many there are. Ex http://jsfiddle.net/mMYrf/6/
Why would u use it? Because if you have a grid of elements, you might want roundcorners on first and last item. You might not want a margin on the first or last item and so on.. :)
This is not about jQuery but about CSS: :first-child and :last-child.
精彩评论