tags:

views:

67

answers:

3

I'm farily new to jquery and can't figure out how to build a series of span elements based on the number of divs in a container. I'm trying to use the jquery.flow plugin to create a slider on a page in my site. My CMS will kick out all the images in divs, but I'd like to automatically create the necessary span elements. I'm trying to make this dynamic, allowing the user to create as many slider images as necessary. The code structure is shown here:

<div id="myController">
<span class="jFlowControl">No 1 </span>
<span class="jFlowControl">No 2 </span>
<span class="jFlowControl">No 3 </span>
<span class="jFlowControl">No 4 </span>
</div>

<div id="mySlides">
<div>First Slide</div>
<div>Second Slide </div>
<div>Third Slide </div>
<div>Fourth Slide </div>
</div>

I'd can easily generate the list of divs inside the container div. I'd like to write a piece of jquery that will add one span for each of the divs. If I have 4 divs, then the script will create the 4 spans. If I have 10 divs, then the script will create 10 spans.

Thanks for any help!

+7  A: 

Try:

 $('#mySlides div').each(function(index){
      $('#myController').append(
           $('<span class="jFlowControl">No ' + (index+1) + ' </span>')
      );
 });

See: http://jquery.nodnod.net/cases/606

thedz
A: 

Something like the following should work.

for (i = 0; i < $("#container div").length; i++) {
    $("#myController").append("<span class=\"jFlowControl\">No " + (i + 1) + "</span>");
}
Max Schmeling
If you're going to use jQuery at all, use the each function to loop.
Josh Stodola
Yeah, I didn't know about the index parameter option that thedz used, otherwise I would have.
Max Schmeling
A: 

Thedz and Max Schmeling solutions both work, but: since this is for a dynamic system where the amount of images could be quite big, watch out for performance issues. Tests have proven that html injection is heavy on the browser. So try only to do one injection by concatenating all the html that has to be injected first. there is a debate whether the concatenation should be done via string concatenation or via array joining. The bottom line is: it depends of the html to be injected, so test in firebug the time each solution takes. Here is the simple string concatenation example.

var imageSpans = '';
$('#mySlides div').each(function(index){
  imageSpans += '<span class="jFlowControl">No ' + (index+1) + ' </span>';    
 });
$('#myController').append(imageSpans);
pixeline