jQuery .clone .insertAfter with a new ID
Asked Answered
H

2

6

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/

Hum answered 8/2, 2012 at 22:42 Comment(1)
@rusty, Where did your answer go, it was correct?Hum
T
9

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/

Television answered 8/2, 2012 at 22:42 Comment(2)
@user1090389: Then you'd do the same thing, but with .each(). I'll update.Excusatory
God I love StackOverflow! One search, first result! Thanks!Primm
C
2

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);
    });

});
Calva answered 8/2, 2012 at 22:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.