0

I'm looking to find image src from external url

This is my function:

<script>
function sompret_image_creator(url, ptitle)
{
    $.ajax(
        { 
        url: url, 
        success: function(data) {
            var img = $.parseHTML( data ).find("img"), 
                len = img.length; 
            if( len > 0 ){
                var src = img.first().attr("src"); // get id of first image
            } else {
                console.log("Image not found");
            }
            console.log(src);

            image_tag='<img src="'+src+'" alt="'+ptitle+'"/>';
            return image_tag;
        } 
    });
}
</script>

I have this error

Uncaught TypeError: Object [object Array] has no method 'find'

3
  • What data do you get back? Can you not just do $(data).find("img");? Commented Jan 15, 2014 at 13:34
  • by any chance is it wrapped in d, like data.d instead of data ? Commented Jan 15, 2014 at 13:35
  • Yes, I would also suggest to do $(data).find("img") instead of $.parseHTML( data ).find("img"). Probably that work... Commented Jan 15, 2014 at 13:38

1 Answer 1

1

Because the data is only html, you need to wrap the $.parseHTML( data ) with $() and then do .find()

<script>
function sompret_image_creator(url, ptitle)
{
    $.ajax(
        { 
        url: url, 
        success: function(data) {
            var html = $.parseHTML( data ), 
                img = $(html).find("img"),
                len = img.length; 
            if( len > 0 ){
                var src = img.first().attr("src"); // get id of first image
            } else {
                console.log("Image not found");
            }
            console.log(src);

            image_tag='<img src="'+src+'" alt="'+ptitle+'"/>';
            return image_tag;
        } 
    });
}
</script>
Sign up to request clarification or add additional context in comments.

22 Comments

thank you very much, but now i need to get the first src of .post class how can i make this ?
$(html).find('img.post').first().attr('src');
.post it's not the class of my images but of my div. <div class="post"> <img src.... /> </div>
$(html).find('.post').find('img').first().attr('src');
I think you need this: $(html).find('.post').find('img:first');
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.