Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


How do you clone an element and change the ID's of it and all its children to be unique? [SOLVED]


I'm trying to duplicate a fieldset, I have managed to get the cloning process.

But now, I want to edit all of its ID's from id="hello" to id="hello-2"

The code I'm trying below just doesn't work and I don't know why! (It's the middle section that is broken).

//When add section is pressed
$('#add-section').click(function () {
    // get the fieldset's children that user is on, and clone it
    var $fieldsetCopy = $('form>:nth-child(' + pageNumber + ')').clone();

    // add '-2' to all id's of the cloned fieldset
    $fieldsetCopy.find("*[id]").each(function () {
        $(this).attr("id", $(this).attr("id") + "-2");

    // add the cloned fieldset within the original
    $fieldsetCopy.appendTo('form>:nth-child(' + pageNumber + ')');


Thanks for posting your solution!

1 Answer

Sorry, I managed to solve the problem. This is the code that works ^