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.

4
  • Don't append inside of a loop. Commented Jan 26, 2013 at 19:03
  • @BenM why can't you append in a loop? Commented Jan 26, 2013 at 19:35
  • 1
    @ExplosionPills, you can, but it's advised againt > stage.learn.jquery.com/performance/append-outside-loop Commented Jan 26, 2013 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? Commented Jan 26, 2013 at 19:52

1 Answer 1

1

.add creates a new collection.

rcItemsContent = rcItemsContent.add(...
Sign up to request clarification or add additional context in comments.

5 Comments

rcItemsContent = rcItemsContent.add($('<div class="rc-item-content clear hidden"><p class="rc-item-context">' + val[0] + '</p>' + val[1] + '</div>').appendTo(rcItemsLi.eq(index++))); still not working, what am I missing?
@Ron does it add anything? You may need .end() after the .appendTo call
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 you can create an empty jQuery collection with var rcItemsContent = $([])
worked. I didnt need the .end() since .appendTo() keep the original selector. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.