0

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/

4 Answers4

1

without a loop, appending only once

$(Array(number+1).join("<div class='dot'></div>")).appendTo('.m-slide-ctrl');
aelgoa
  • 1,193
  • 1
  • 8
  • 24
  • In case someone like me didn't understand what this means, here's more explanation (http://stackoverflow.com/questions/202605/repeat-string-javascript) – Mohammed Joraid Feb 02 '14 at 21:34
  • 2
    That's not a jQuery object so it doesn't have `appendTo` method. – Ram Feb 02 '14 at 21:39
0

Simply use a for loop

for (var i=0;i<number;i++)
{
    $(dot).appendTo('.m-slide-ctrl');
}

DEMO

Satpal
  • 132,252
  • 13
  • 159
  • 168
0
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.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

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>');
});
plalx
  • 42,889
  • 6
  • 74
  • 90