Addclass add every time in every clone

This is my script

 var newclass = 0;

 jQuery("#addexperience").click(function(){
    $("#expclone").clone().find("input:text").val("").end().prependTo( ".exp_clone" );
    $(".ongoing").each(function(){
        $(".ongoing").addClass("newclass"+newclass);
        newclass++;
    });
 });

I am trying to clone an articular div and add a class to the clone element. but addClass is added every time

means in the first clone he added: newclass1, in the second clone he added: newclass1 newclass2; etc.

I want only newclass2 in the second clone, and newclass3 in the dash of the clone, etc.

+4
source share
4 answers

You should use $(this)inside the callback .each:

$(".ongoing").each(function(){
    $(this).addClass("newclass"+newclass);
    newclass++;      
});

Or you do not even need a variable newclass, .addClasstake the function as a parameter:

$(".ongoing").addClass(function(index) {
  // index is start from 0
  return "newclass" + (index + 1);
});
0
source

, , , , . , , addClass . .each() :

$(".ongoing").last().addClass('newClass'+newclass);
newclass++; 
0

change this line:

$(".ongoing").addClass("newclass"+newclass);

at

$(".ongoing").removeClass().addClass("newclass"+newclass);

it will remove all previous classes .ongoingand add a new class to it. if you want to have a class .ongoing, try like this:

$(".ongoing").removeClass().addClass("ongoing newclass"+newclass);
0
source

Try it,

var newclass = 0;
jQuery("#addexperience").click(function(){
    $clone=$("#expclone").clone()
    $clone.find("input:text").val("");
    $clone.find(".ongoing").removeAttr('class') // remove all classes
          .addClass('ongoing'); // again add ongoing class
    $clone.find(".ongoing").each(function(){
        $(this).addClass("newclass"+newclass);
        newclass++;
    });
    $clone.prependTo(".exp_clone");
});

But it is better to add a new idinstead of the new class.

0
source

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


All Articles