jQuery clone duplicate IDs

Viewed 46424

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 added (this is simple enough using jQuery).

$("#MainConfig").clone(false).appendTo($("#smallConfig"));

The problem, however, is that all the lists and their associated list items have IDs and clone duplicates them. Is there an easy way to replace all these duplicate IDs using jQuery before appending?

9 Answers

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.

$("#MainConfig")
    .clone(false)
    .find("ul,li")
    .removeAttr("id")
    .appendTo($("#smallConfig"));

Try that on for size. :)

[Edit] Fixed for redsquare's comment.

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.

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_'.

Related