Last active
December 17, 2015 05:09
-
-
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!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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()); | |
} | |
}) | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<section> | |
<div data-repeat="10">This is my content</div> | |
</section> |
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());
}
})
});
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
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.