Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

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

Hey!

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!

Thanks for posting your solution!

1 Answer

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