Simplicity
Simplicity

Reputation: 48976

:first-child and :last-child

I'm really not getting the idea of :first-child and :last:child clear. Can you just show an example that clarifies those two filters?

Upvotes: 0

Views: 1709

Answers (4)

Marco Johannesen
Marco Johannesen

Reputation: 13134

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.. :)

Upvotes: 1

sougonde
sougonde

Reputation: 3618

This is not about jQuery but about CSS: :first-child and :last-child.

Upvotes: 0

Shef
Shef

Reputation: 45599

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.

Upvotes: 3

Royi Namir
Royi Namir

Reputation: 148744

 <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

Upvotes: 1

Related Questions