2

Is it possible to chain styles to a jquery append function? I am trying to achieve something like this. but its currently not working out very well. I might be taking the wrong approach.

for (i = 0; i < store.image().length; i++) {
     $('#carousel-inner')
          .append($("<div> </div>"))
          .addClass("shop-image item")
          .css('background-image', 'url(' + store.image()[i] + ')');
     }
}
sirFunkenstine
  • 8,135
  • 6
  • 40
  • 57
  • I would think that 'store.image()' should be an array, at least that's how you are trying to use it, but what is in the store.image() function? – dezman Jun 12 '13 at 14:57
  • Here you are adding class and styling #carousel-inner, not appended elements – A. Wolff Jun 12 '13 at 14:58
  • ¡Now, you have four great answers! Pick five of them noW! – SpYk3HH Jun 12 '13 at 15:18
  • Thanks for all the GREAT answers! @watson im using a knockout observable array syntax. I used the first answer and it worked really well. Also i was calling the function before my array was ready so i had to move my code a bit. Thanks everybody! – sirFunkenstine Jun 12 '13 at 15:27

5 Answers5

4

If you want to add the class and background to the new div element, then you can do it like this:

for (i = 0; i < store.image().length; i++) {
    var $div = $('<div>').addClass('shop-image item')
                         .css('background-image', 'url(' + store.image()[i] + ')');

    $('#carousel-inner').append($div);
}
Sven van Zoelen
  • 6,989
  • 5
  • 37
  • 48
3

If you're trying to add class and background to the new inner div element then it would be more like:

for (i = 0; i < store.image().length; i++) {
    $('#carousel-inner').append(
        $("<div />").addClass("shop-image item")
            .css('background-image', 'url(' + store.image()[i] + ')')
    );
}

As is in your question, it's adding the class and bg image to #carousel-inner, not to the div inside.

Also, have you console logged store.image()[i] to make sure you're getting the link expected? If not, just inside your for statement, add console.log("image["+i+"]:", store.image()[i]) and check developer console to see what you get.

You can also add multiple items in an append, each with it's own properties simply by adding , between each one, and even append to inner elements!

for (i = 0; i < store.image().length; i++) {
    $('#carousel-inner').append(
        $("<div />").addClass("shop-image item")
            .css('background-image', 'url(' + store.image()[i] + ')'),  //  <-- see the pretty comma!
        $("<div />").addClass("shop-image item")
            .css('background-image bg-copy', 'url(' + store.image()[i] + ')'),  //  <-- see the pretty comma!
        $("<span />", { text: "I'm a Silly String!" }).addClass("silly-string")
            .append(    //  here i add an inner element to this span!
                $("<span />", { text: " I'm inside this silly string!" })
            )
    );
}
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
2

You could use appendTo():

for (i = 0; i < store.image().length; i++) {
     $('<div/>')
          .addClass("shop-image item")
          .css('background-image', 'url(' + store.image()[i] + ')')
          .appendTo('#carousel-inner');
}
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
2

You really shouldn't be calling the function just to get a length of something. Unsure what store.image() returns, but I'm guessing it's something that looks like an array, and to iterate the result and just call the function once, you can use $.each.
To set attributes on a newly created element inside such a loop, you'd do something like this :

$.each(store.image(), function(i, img) {
    $('<div />', {
                  'class':'shop-image item',
                   style : 'background-image : url('+img+');'
                 }
    ).appendTo('#carousel-inner');
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

JQuery's append function seems to return the container object. So what you're doing on each iteration is overwriting the CSS of #carousel-inner.
The easiest answer and best answer is to use appendTo-- as mentioned above by A. Wolff-- since it returns the element you just created.

Here's another possible solution that will emphasize the issue you ran into:
First append a new div. Then select the div you just created.

var colors = ["#0F3D4C", "#1F7A99", "#2EB8E6", "#5CD6FF", "#99E6FF"];
for (var i = 0; i < colors.length; i++)
{
    $('#colors_container')
    .append("<div></div>");
    $('#colors_container div:last-child')
    .html("Color " + i)
    .css('background-color', colors[i]);
 }

Note for all D3 fans out there: D3's append does not work this way.
When you append an element in D3, D3's append returns the child you just created. You can then chain to it another function without doing all this extra work.

I ran into this because I ran into a situation where I wanted to change some code from
d3.select("#" + container).append("div")
to
$("<div></div>").appendTo("#" + container)