views:

7767

answers:

4

I have a 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 thier associated list items have Ids and clone duplicates them. Is there an easy way to replace all these duplicate id's using JQuery before appending?

+8  A: 

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

Try that on for size. :)

[Edit] Fixed for redsquare's comment.

Salty
I would remove the id's before running the append otherwise your duplicating the id's in the dom still which could have nasty effects
redsquare
That' essentially what Salty is doing in his example I think. I will give it a go but I would rather use a global find for all children in case the markup changes and other elements within the parent get duped
Sheff
No problem. Thank you for catching my mistake =]
Salty
Thanks this was very useful in that I could take `$('#itemBase').clone(true).removeAttr('id').attr('id','item'+nextItemId++).removeClass('hidden').addClass('item').insertAfter($('#itemBase'));`
dlamblin
A: 

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.

Danita
+9  A: 

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.

Crescent Fresh
Can something similar not be achieved but replace the ids?
Sheff
Then you must track how the ids were changed (ie, prefix, postfix) and use string concatenation to reconstruct the correct ids when referencing the cloned elements. Annoying. Just use classes.
Crescent Fresh
+2  A: 

I use something like this: $("#details").clone().attr('id','details_clone').after("h1").show();

Oh that's even shorter: `var i=$('#itemBase'); i.clone(true).attr('id','item'+nextItemId++) .removeClass('hidden').addClass('item').insertAfter(i);`
dlamblin