Select first <img> in div?

Select first <img> in div?

Hi all

I’m using the jquery cycle plugin - http://www.malsup.com/jquery/cycle/ in a wordpress theme.

All the images flash up before the slideshow kicks in

The FAQ recommends hiding the images then showing the first image.


#slideshow img { display: none }
#slideshow img.first { display: block }

Because the image are output from Wordpress I can’t add a class to the first image


<div id="slideshow">
      <p><img class="ngg-singlepic ngg-none" src="http://wordpress/wp-content/gallery/home/7.jpg" alt="7" /></p>
      <p><img class="ngg-singlepic ngg-none" src="http://wordpress/wp-content/gallery/home/6.jpg" alt="6" /></p>
      <p><img class="ngg-singlepic ngg-none" src="http://wordpress/wp-content/gallery/home/5.jpg" alt="5" /></p>
      <p><img class="ngg-singlepic ngg-none" src="http://wordpress/wp-content/gallery/home/3.jpg" alt="3" /></p>
      <p><img class="ngg-singlepic ngg-none" src="http://wordpress/wp-content/gallery/home/1.jpg" alt="1" /></p>
      <p>&nbsp;</p>
</div><!-- #slideshow -->

I tried selecting the first img with


#slideshow img.ngg-singlepic:first-child {
	display: block
}

but this seems to address all the img’s

Is there a way to address the only the first img

there’s a Fade In First Image Demo in jquery cycle site did you see that.

$(function() {
$(‘#slideshow img:first’).fadeIn(1000, function() {
$(‘#slideshow’).cycle();
});
});

What you need is

#slideshow p:first-child img {display:block;}

:first-child targets any element that is the first child of its parent. So in this example, every <img> is the first child of its parent <p>. It doesn’t matter that you didn’t include the ‘p’ in your CSS. So what you need is to target the image inside the paragraph that is the first child of the <div id=“slideshow”>.

I feel this is worth saying due to the fact you comment your HTML. In IE7 the first-child pseudo class is buggy. If you have a comment interrupting hte first-child, it will select the comment instead of the actual element you want. So be careful where you comment, in case you still have support for IE7 (which is still kicking :)).

Also note that if you dynamically add elements (CSS or JS), it won’t select that instead, so be wary of that. Not really applicable in your situation but as I was mentioning the comment bug to you, it seemed applicable to mention this other bug :).