I have an HTML element with a large collection of unordered lists contained within it. I need to clone this element to place elsewhere on the page with different styles adde
Here is a solution with id.
var clone = $("#MainConfig").clone();
clone.find('[id]').each(function () { this.id = 'new_'+this.id });
$('#smallConfig').append(clone);
if you want dynamically set id, you can use counter instead of 'new_'.
I believe this is the best way
var $clone = $("#MainConfig").clone(false);
$clone.removeAttr('id'); // remove id="MainConfig"
$clone.find('[id]').removeAttr('id'); // remove all other id attributes
$clone.appendTo($("#smallConfig")); // add to DOM.
If you need a way to reference the list items after you've cloned them, you must use classes, not IDs. Change all id="..." to class="..."
If you are dealing with legacy code or something and can't change the IDs to classes, you must remove the id attributes before appending.
$("#MainConfig").clone(false).find("*").removeAttr("id").appendTo($("#smallConfig"));
Just be aware that you don't have a way to reference individual items anymore.
I use something like this: $("#details").clone().attr('id','details_clone').after("h1").show();
FWIW, I used Dario's function, but needed to catch form labels as well.
Add another if statement like this to do so:
if(element.htmlFor){
var matches = element.htmlFor.match(/(.+)_\d+/);
if(matches && matches.length >= 2) // Captures start at [1].
element.htmlFor = matches[1] + "_" + cur_num;
}
If you will have several similar items on a page, it is best to use classes, not ids. That way you can apply styles to uls inside different container ids.