Reputation: 27
I'm currently working with the Tumblr API and trying to append each post. I would like to keep the caption and date published with the photo so I'm attempting to use the clone() method. Every time a post is appended it doubles. So the first post is one photo, the second is two of the same photo, third is four of the same photo, etc.
here's the HTML:
<section class='site-content'>
<span class="fa fa-bars"></span>
<div class="tumblr">
<div class="blog_content">
<div class="blog_text">
<p class="date"></p>
<p class="caption"></p>
</div>
<div class="blog_media">
<img class="blog_photo" src="" />
<div class="blog_video">
</div>
</div>
</div>
</div>
</section>
here is a code snippet:
for (var i = 0; i < 10; i++) {
var type = results.response.posts[i].type;
if (type === 'photo') {
var photo = $('.blog_content').clone();
photo.find('.caption').html(results.response.posts[i].caption);
photo.find('.date').text(results.response.posts[i].date);
photo.find('.blog_photo').attr('src', results.response.posts[i].photos[0].original_size.url);
$('.tumblr').append(photo);
}
Can anybody spot where I'm making my mistake?
Upvotes: 0
Views: 134
Reputation: 15923
Use .first()
to get the first of the .blog_content
type and clone it
var photo =$('.blog_content').first().clone();
Upvotes: 1
Reputation: 46
You're running $('.blog_content').clone()
in the loop repeatedly, which selects $('.blog_content')
every time you run it and .clone()
will return an array of all selected elements.
Since this cloned set is then appended back, the selector will then clone 2, then 4, ... until the for
loop terminates because that's how the DOM is structured at the time the selector is run.
You will need to either cache the value of the cloned DOM element outside of the loop or make your selector more specific to only return one element at a time.
Upvotes: 2