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 Javascript Var imageSrc = $('. Post_Container Img'). Attr('Src'); $(". appendedimageContainer")...
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?
2 Answers
Use nth-child selector to obtain your desired image, e.g.
var imageSrc = $('.post_container img:nth-child(0)').attr('src');
you can use first() to get the first element :-
var imageSrc = $('.post_container img').first().attr('src');