I am looking to only show the first image in each div with the class name "className."
This...
<div class="className">
<p>Yo yo yo</p>
<p><img src="snoop.jpg" /></p>
</div>
<div class="className">
Helloooooo
<img src="biggie.jpg" />
<img src="tupac.jpg" />
<img src="coolio.jpg" />
Blah blah blah
</div>
<div class="className">
<div><img src="dmx.jpg" /></div>
<div><img src="willsmith.jpg" /></div>
</div>
Would display as...
[snoop.jpg]
[biggie.jpg]
[dmx.jpg]
Only the first image from each div with a className would be shown, without the additional content. The content is subject to change frequently.
Attempts at jQuery:
var imgarray = $(".className").find("img:first").attr('src');
for(i = 0; i < imgarray.length; i++){
$('body').append('<img src=\"'+imgarray[i]+'\">');
}
...
(trying to obtain the SRC of each image...)
$('.className').each(function() {
alert( $('img').attr('src') );
});
Having trouble getting it to work. Appreciate any help! I primarily focus on front-end HTML/CSS and am not very experienced with jQuery.
EDIT: Fixed typos (missing quote marks after image SRC's)
UPDATE: Thank you everyone for your assistance! Implemented the recommended solution as follows:
<style type="text/css">
.className {
display: none;
}
</style>
<div class="className">
<p>Yo yo yo</p>
<p><img src="snoop.jpg" /></p>
</div>
<div class="className">
Helloooooo
<img src="biggie.jpg" />
<img src="tupac.jpg" />
<img src="coolio.jpg" />
Blah blah blah
</div>
<div class="className">
<div><img src="dmx.jpg" /></div>
<div><img src="willsmith.jpg" /></div>
</div>
<script type="text/javascript">
$('.className').each(function() {
var imagesrc = $(this).find('img').first().attr('src') ;
$('body').append( '<img src=\"' + imagesrc + '\">');
});
</script>