Search code examples
javascriptjqueryjsondynamictumblr

Jquery: Wrap dynamically created content sourced from API


I am using the Tumblr API to create a news feed on my site. Currently, for each post the API returns:

<div class="posttitle">TITLE</div>
<div class="postbody">content</div>

To make styling easier, I want to wrap these in a div, so I wrote:

$('#newsbox > .posttitle').each(function(){
    $(this).next('.postbody').andSelf().wrapAll('<div class="tumblrpost"/>');
});

However, I cannot get this to work. Could this be because the Tumblr posts are dynamically created and are not part of the DOM first off, when the JQuery runs?

I have positioned the above script after the API script, but no difference.

Would anyone know the correct way of achieving this wrap?

EDIT:

API: http://jsfiddle.net/tgAUJ/


Solution

  • An updated fiddle with the correct code is now available there: http://jsfiddle.net/tgAUJ/1/ .

    What I have done is simply put your code in the results function after the while. I have also corrected the while so that, if you have less than 5 entries being returned (unlikely but possible), it will not bug out. Mod is as follows:

    if (!results.response.posts[i]) break;
    

    Note that you'll have to put your private key back in.