Creating Unique Class Names when Creating/Cloning New Elements Using Javascript (jQuery)



  • *****Hello i am curently working on how to clone a div and then assign new classes to it , it works actually but everytime the clone div is made they all have same new classes, how can make them all have different classes thanks


    $(".postingContent").on("click", function () {
          //function to use to clone;
            var newItem = function () {
                var cloneCount = 0;
                cloneCount++;
                return $('.UserContentLi')
                    .clone(true, true)
                    .attr({'class': 'clon_' + cloneCount++}).insertAfter($('[class^=UserContentLi]:last'))  
                    .appendTo(".wholeUserContentLayer")
                     //changing classes for output text user wrote
                    .find(".textsUserWroteOnline").attr({ 'class': "textsUserWroteOnlineNew" + cloneCount++ }).addClass("textsUserWroteOnlineNewClass");
            };
            //cloning element i want
             newItem($(".UserContentLi").each(function () {
                $(".textsUserWroteOnline").html($(".bioInput").val());
             
            })); 
           
            
    
        });
    


  • @Abdullah

    One thing that stands out is that you are resetting cloneCount every-time newItem is called. So move 'var cloneCount = 0;' to the top of the javascript file? That is just one option.



  • @Abdullah

    One thing that stands out is that you are resetting cloneCount every-time newItem is called. So move 'var cloneCount = 0;' to the top of the javascript file? That is just one option.



  • @avan Thaaaaaaaaaaaaaaaanks very much, i freaking appreciate this website,always learning ,it worked thanks 😀


Log in to reply