I want to dynamically generate 8 new paragraphs with jQuery:
http://jsfiddle.net/johnhoffman/Dfydn/
However, this snippet of jQuery only adds a single paragraph to my div (with the text “7” in it).
var attached = $("<p>");
var sandbox = $("#sandbox");
for (var i = 0; i < 8; i++) {
// How come reseting attached works? attached = $("<p>");
attached.html(i).appendTo(sandbox);
}
HTML: <div id="sandbox"></div>
I do not want to run attached = $("<p>"); for every iteration of the loop because I want to make use of the prototype design pattern – I want to build a paragraph and then alter copies of it to preventing having to build from scratch every time. How do I make a deep copy of a dynamically created element?
You might try this. Use the
.clone()method. Also you don’t need the .html(i) when you’re using clone(). Because clone returns a jQuery object you don’t even need to wrap a $() around it.Also if you want to clone the event handlers you should use .clone(true). See http://api.jquery.com/clone/ for more info about
clone()