3

how can I turn this into something faster:

$.each(data, function(key, val) 
{ 
    rcItemsLi.eq(index++).append('<div class="rc-item-content clear hidden"><p class="rc-item-context">' + val[0] + '</p>' + val[1] + '</div>'); 
}); 
rcItemsContent = $('.rc-item-content');

in this example, I first append the elements to where I want, then I use .rc-item-content selector to "find" all the elements and store them in rcItemsContent variable.


for example:

$.each(data, function(key, val) 
{ 
    rcItemsContent.add($('<div class="rc-item-content clear hidden"><p class="rc-item-context">' + val[0] + '</p>' + val[1] + '</div>').appendTo(rcItemsLi.eq(index++))); 
});

in this example, what I'm trying to achieve (which of course I don't), is to add / chain the element in the variable and append it to where I want at the same time.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
Ron
  • 3,975
  • 17
  • 80
  • 130
  • Don't append inside of a loop. – BenM Jan 26 '13 at 19:03
  • @BenM why can't you append in a loop? – Explosion Pills Jan 26 '13 at 19:35
  • 1
    @ExplosionPills, you can, but it's advised againt > http://stage.learn.jquery.com/performance/append-outside-loop/ – BenM Jan 26 '13 at 19:37
  • @BenM is there a way to append one element from collection to one element in other collection, for example I got collection of 3 divs, and collection of 3 paragraph, I want to paragraph 1 will be appended to div 1, paragraph 2 to div 2 and paragraph 3 to div 3, without using a loop? – Ron Jan 26 '13 at 19:52

1 Answers1

1

.add creates a new collection.

rcItemsContent = rcItemsContent.add(...
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • `rcItemsContent = rcItemsContent.add($('').appendTo(rcItemsLi.eq(index++)));` still not working, what am I missing? – Ron Jan 26 '13 at 19:29
  • @Ron does it add anything? You may need `.end()` after the `.appendTo` call – Explosion Pills Jan 26 '13 at 19:35
  • I think that the problem is how I declared the variable rcItemsContent - I declared it this way: `var rcItemsContent`. maybe I need to declare it as jquery variable / object / w.e and I dont know how – Ron Jan 26 '13 at 19:39
  • @Ron you can create an empty jQuery collection with `var rcItemsContent = $([])` – Explosion Pills Jan 26 '13 at 19:41
  • worked. I didnt need the `.end()` since `.appendTo()` keep the original selector. Thank you very much. – Ron Jan 26 '13 at 19:45