I have a jQuery problem that I can’t seem to work out on my own – while I know how to style the the first and last elements of an unordered using the :first-child and :last-child selectors, I’d like to include a caption inside the UL as well…
I need to put the caption before or after the LI elements inside the UL, but this makes jQuery apply :first-child or :last-child to the P element depending on where it sits in relation to the list of LI elements.
Basically, I’d like to find out how to make :first-child and :last-child selector exclude the P element altogether. Having looked around, I’ve been able to work out that .not() is probably what I need, but haven’t been able to get it to work.
For example, this does not work –
$('ul.grid li:first-child').not($(.caption)).addClass('narrow');
I’d be very grateful if anybody would be able to help me out based on the below
jQuery( document ).ready( function ($) {
$('ul.grid li:first-child').addClass('narrow');
$('ul.grid li:last-child').addClass( 'narrow' );
});
HTML:
<ul class="grid">
<p class="caption">Caption text</p>
<li>
<img src="images/test1.jpg" alt="1" />
</li>
<li>
<img src="images/test2.jpg" alt="2" />
</li>
<li>
<img src="images/test2.jpg" alt="2" />
</li>
</ul>
Ok, I think I understand. Does this work?