views:

60

answers:

1

Let's say we have this unidentified DIV

  <div class="class-occurs-many-times-on-page">foo</div>

and we want to place right after it another unidentified DIV that contains dozens or hundreds of SPAN elements:

<div class="a-class-that-occurs-many-times-on-page">foo</div>
<div class="another-class-that-occurs-many-times-on-page">
        <span class="latin">lorem</span><span class="latin">ipse</span>
        <span class="swedish-chef">føø</span><span class="swedish-chef">bår</span>
        .
        .
        .
        <span>...</span>
</div>

And we have added the first unidentified DIV and want to add the SPAN-container DIV in this way:

 values = [{word: "lorem", cls: "latin"}, {word: "ipse", cls: "latin"},
 {word:"føø",cls:"swedish-chef"}, {word:"bår",cls:"swedish-chef"}];

 $("#" +  someParentElement).append(
     $("<div></div>").addClass("a-class-that-occurs-many-times-on-page").text("foo").after(

            $("<div></div>").addClass("another-class-that-occurs-many-times-on-page").append(
                 function(index, html){                    
                     // how to wrap each value in the values array in a span
                     // and inject each of those spans into this DIV?

                 }
            )

      )


 );

Is this approach possible, and if so, what does the function inside the .append() method invocation have to do on each iteration of the values array, if the goal is to wrap each of the values in the array in a SPAN and inject that span into the container?

Thanks

A: 
values = [{word: "lorem", cls: "latin"}, {word: "ipse", cls: "latin"}, {word:"føø",cls:"swedish-chef"}, {word:"bår",cls:"swedish-chef"}],
len    = values.length,
$ctn   = $('<div/>', {
     class:   'another-class-that-occurs-many-times-on-page'
}),
buildarr = [];

while(len--){
    buildarr.push('<span>');
    buildarr.push(values[len].word);
    buildarr.push(values[len].cls);
    buildarr.push('</span>');
}

$ctn.append(buildarr.join('')).appendTo(document.body);

That is just a suggestion like you could accomplish that kind of task. It assumes the order in which we have to fill the array is irrelavant (by looping with the fastest way, reversed while). If the order is important use a standard for loop.

jAndy
Thanks, jAndy. The suggestion is helpful, but in creating a reference to $ctn, you are sidestepping the question/problem: I was wondering if it's posible to accomplish this using only the chaining approach.
Tim