jqueryjsontumblr

Fetching a photo in a Tumblr text post using jQuery and JSON


My background in jQuery and JSON is fairly weak, so I'm learning the Tumblr API as I go along. I'd like to fetch the src attribute from first photo in the most recent "regular-post." The image in the post has a class of "main".

Thus far I've been able to fetch the post title into a span and the post URL into a hyperlink that encompasses the image / span.

$(document).ready(function () {
    $.getJSON('http://features.futurevague.com/api/read/json?callback=?',
        function(response) {
           $('a#feat0').attr('href',response.posts[0].url);
           $('span#feat0').wrapInner(response.posts[0]['regular-title']);
           $('img#feat0').attr('src',response.posts[0]['regular-body'].find('img.main')[0].attr('src'));
    });
});

The third function, however, does not work (and is probably malformed).

My HTML I'm embedding the content into looks like this:

<a href="#" id="feat0">
    <div class="imgholder">
        <img src="#" class="main" id="feat0">
    <span id="feat0"></span></span>
    </div>
</a>

So any help using the jQuery .find() method?


Solution

  • You shouldn't have 2 ids with the same value, for starters. Also, post the value of response.posts[0]['regular-body'], it will help.. Remove the id from the span and go

    $('#feat0').find('img:first').attr('src', response.posts[0]['regular-body']);
    

    From the comment in your post : response.posts[0] is a String here and not HTML ! So you can't use "find" on it. You should go regex or even indexOf to extract the image source.