Reputation: 15372
So I have some HTML that I would like to be cloned several times and appended to the document. It's just typical HTML form stuff. But since things like <label for="something">
works based on element IDs, it would be nice if each HTML element within the jquery clone()
'd element could have a unique ID, apart from all their cloned counterparts. Just as a guess to how I could do this, I wonder if it would be possible to make the IDs within my initial element all contain some unique string. I could then somehow traverse the element and replace that string with a _1,_2,_3 etc.
I haven't gotten very far, but it seems like something like this should work.
$(document).ready(function(){
var toReplace = "containerUniqueCharacterString1234";
var copy = $('#containerUniqueCharacterString1234').clone(true);
copy[0].style.display = "block"; //so i can reference the first element like this
console.log(copy[0]); //[object HTMLDivElement]
$('body').append(copy);
$.each(copy, function(index, value){
var children = copy[index].childNodes;
console.log(children); //[object NodeList]
var len = children.length;
if (copy[index].childNodes.length > 0){
if (copy[index].childNodes.hasOwnProperty('id')){
//replace the toReplace string with an incremented number here(?)
//annnnd this is where i've gotten in too deep and made this overly complex
}
}
$('#otherResults').append(len);
});
});
http://jsbin.com/ecojub/1/edit
Or perhaps there's a much much simpler way to do this. Thanks!
Upvotes: 0
Views: 302
Reputation: 708
If you are copying HTML elements many times for display only, maybe you should consider using a templating engine rather than copying the DOM elements, which are expensive and less maintainable. underscore has a pretty easy to use function, http://documentcloud.github.com/underscore/#template
Upvotes: 1