Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery clone duplicate IDs

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?

like image 676
Sheff Avatar asked Jan 06 '09 10:01

Sheff


People also ask

How to clone using jQuery?

To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.

How do I clone a div with another ID?

To clone an element and change its id: Use the cloneNode() method to clone the element. Set a different id property on the element. For example, clone.id = 'another-id' .

How does jQuery clone work?

The . clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.

How do I clone a div?

To clone a div and change its id with JavaScript, we can use the cloneNode method on the div. Then we can set the id property of the cloned element to set the ID. to add the div.


1 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.

like image 161
Crescent Fresh Avatar answered Sep 25 '22 06:09

Crescent Fresh