Skip to content

Instantly share code, notes, and snippets.

@elliottkember
Last active December 17, 2015 05:09
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save elliottkember/5555563 to your computer and use it in GitHub Desktop.
Save elliottkember/5555563 to your computer and use it in GitHub Desktop.
Ever wanted to repeat parts of your markup while building templates? Do it like this!
$(function(){
$('*[data-repeat]').each(function(){
var n = $(this).data('repeat');
var parent = $(this).parent();
self = $(this);
for (var i = 0; i < n; i++) {
self.after(self.clone());
}
})
});
<section>
<div data-repeat="10">This is my content</div>
</section>
@markjs
Copy link

markjs commented May 10, 2013

You'd be better off replacing .parent().append(... with .after(... on line 5 so if the parent element contains other content the repetition will be appended in the right place.

@markjs
Copy link

markjs commented May 10, 2013

And now you've revised it so my comment doesn't make sense. Basically, I prefer this instead:

$(function(){
  $('*[data-repeat]').each(function(){
    self = $(this);
    var n = self.data('repeat');
    for (var i = 0; i < n; i++) {
      self.after(self.clone());
    }
  })
});

@elliottkember
Copy link
Author

Makes sense! I was actually using something like that in another version somewhere but lost it. Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment