Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 571
henryaaron Avatar asked Feb 08 '12 22:02

henryaaron


2 Answers

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/

like image 188
2 revsuser1106925 Avatar answered Nov 20 '22 14:11

2 revsuser1106925


I believe you'll need to .each() of them to handle them individually. What the code is currently doing is grabbing all of them and cloning them after all of them. Instead, you want to handle each of them individually and insert the clone after the original, after changing the classes around as desired.

$(document).ready(function(){

    $('div.reflection').each(function () {
        var org = $(this),
            clone = org.clone();

        clone.removeClass('reflection').addClass('reflected')
            .insertAfter(org);
    });

});
like image 24
Overflowed Avatar answered Nov 20 '22 12:11

Overflowed