Search code examples
javascriptjquerycloneaddclassinsertafter

jQuery .clone .insertAfter with a new ID


How can I clone a DIV, append it right after the div and give it a new identifier?

I have a DIV with a class reflection, I want each instance of this DIV, cloned, and inserted right after the original, but with the class reflected (without the class, reflection) How can I accomplish this with jQuery?

Here's my current fiddle, but it doesn't work right... http://jsfiddle.net/yUgn9/


Solution

  • Pass a function to .after(), and have it return the updated clone.

    $('div.reflection').after(function() {
        return $(this).clone().toggleClass('reflection reflected');
    });
    

    DEMO: http://jsfiddle.net/PFBVX/


    In older versions of jQuery, do this...

    $('div.reflection').each(function() {
        $(this).after($(this).clone().toggleClass('reflection reflected'));
    });
    

    DEMO: http://jsfiddle.net/PFBVX/1/