get image src if there is more then image src just get one image src

I am trying to get image src using jquery like this:

HTML

<div> <img src="">
</div>
<div></div>

Javascript

var imageSrc = $('.post_container img').attr('src');
$(".appendedimageContainer").append('<div><img src="'+imageSrc+'"></div>');

The code above works in a healthy way, but the question I would like to ask is here. If the pictures are more than one I want them not to be append. I just want to get one of them append.

For example if a situation as follows:

<div> <img src=""> <img src=""> <img src=""> <img src="">
</div>
<div></div>

Just let one of them get a image url and ignore other image src. Can you help How can I do this?

1

2 Answers

Use nth-child selector to obtain your desired image, e.g.

var imageSrc = $('.post_container img:nth-child(0)').attr('src');
1

you can use first() to get the first element :-

var imageSrc = $('.post_container img').first().attr('src');

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like