Reputation:
I've got a string within a variable:
var dot = '<div class="dot"></div>'
And I am trying to append it to some HTML, multiple times:
var number = 3; // this has come from an $('img').length; could be any number
$(dot * number).appendTo('.m-slide-ctrl');
The above obviously does not work, but I'm not sure how to approach something so simple. The number of times I would like the string to be written, would be dependent on the number of images (so using .length)
Any help would be great.
http://jsfiddle.net/tmyie/VE75U/
Upvotes: 0
Views: 738
Reputation: 1201
without a loop, appending only once
$(Array(number+1).join("<div class='dot'></div>")).appendTo('.m-slide-ctrl');
Upvotes: 1
Reputation: 206008
var slides = $('.m-slide img'); // Images in gallery
var n = slides.length; // count images
var dots = ''; // HTML string
for(var i=0; i<n; i++){
dots += '<div class="dot"></div>'; // Create buttons
}
$('.m-slide-ctrl').append( dots ); // Append them
// outside the loop. Faster!
there's no reason to force jQuery to lookup your DOM several times for the same element, and for every iteration .append()
to that element some HTML, if all of that can be done only once outside the loop. Makes sense? Also, the native for loop is faster than any other jQuery loop method.
Upvotes: 0
Reputation: 43718
Well if it comes from $('img').length
, you could just do something like:
var $dotDivProto = $('<div class="dot"></div>');
$('.m-slide-ctrl').append($('img').map(function () {
return $dotDivProto.clone();
});
Or simply parsing every time:
$('.m-slide-ctrl').append($('img').map(function () {
return $('<div class="dot"></div>');
});
Upvotes: 0