JQuery.clone.insertAfter with new id

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

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

Here is my current fiddle, but it does not work correctly ... http://jsfiddle.net/yUgn9/

+6
source share
2 answers

Pass the .after() function and return the updated clone.

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

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


In older jQuery versions do this ...

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

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

+9
source

I believe that you will need .each () of them to process them individually. What the code is currently doing is capturing all of them and cloning them after all of them. Instead, you want to process each one individually and insert the clone after the original after changing the classes as desired.

 $(document).ready(function(){ $('div.reflection').each(function () { var org = $(this), clone = org.clone(); clone.removeClass('reflection').addClass('reflected') .insertAfter(org); }); }); 
+2
source

Source: https://habr.com/ru/post/907991/


All Articles