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 class="post_container"> 
   <img src="">
</div>
<div class="appendedimageContainer"></div>

Javascript

var imageSrc = $('.post_container img').attr('src');
$(".appendedimageContainer").append('<div class="appended"><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 class="post_container"> 
   <img src="">
   <img src="">
   <img src="">
   <img src="">
</div>
<div class="appendedimageContainer"></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

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

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest