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?
12 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');