Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone div and remove class without changing the original one

I want to clone the content of the div using jQuery, but from the copied content I want to remove the class from the original one before I use appendTo function. When I remove the class from a clone they also remove from the original one.

My code is:

$('.carousel .item').each(function(){
        var next = $(this).next();

        if (!next.length) {
            next = $(this).siblings(':first');
        }
        next.children(':first-child').clone().appendTo($(this));
        next.children(':first-child').addClass('col-sm-offset-1');

        for (var i=0;i<3;i++) {
            next=next.next();
            if (!next.length) {
                next = $(this).siblings(':first');
            }
            next.children(':first-child').clone().appendTo($(this));                 
        }

});

Please note, I don't want to remove class from actual div from where I copied the content, I just want to remove it from the copied code so that it is not included in the cloned div.

like image 801
suraj Avatar asked May 25 '17 06:05

suraj


2 Answers

You can use removeClass and addClass after clone like this.

 .clone().removeClass('oldClass').addClass('col-sm-offset-1')
like image 154
4b0 Avatar answered Sep 30 '22 07:09

4b0


You can remove element from cloned object first and then clone to your new object which would be something like shown below:

$('.carousel .item').each(function(){ var next = $(this).next();    
        if (!next.length) {
            next = $(this).siblings(':first');
        }
        var $block = next.children(':first-child');

        // Grab the and remove element class
        $block = $block.find('.your-element-identity-class').removeClass('your-element-identity-class');

        // Clone the block 
        var $clone = $block.clone();

        $clone.appendTo($(this));
        next.children(':first-child').addClass('col-sm-offset-1');

        for (var i=0;i<3;i++) {
            next=next.next();
            if (!next.length) {
                next = $(this).siblings(':first');
            }
            var $block = next.children(':first-child');

            // Grab the and remove element class
            $block = $block.find('.your-element-identity-class').removeClass('your-element-identity-class');

            // Clone the block 
            var $clone = $block.clone();

            $clone.appendTo($(this));                
        }

    });

Replace "your-element-identity-class" with your class name you want to remove. Original ref. from - How to remove the selected element during a clone() operation

like image 32
Rupal Javiya Avatar answered Sep 30 '22 06:09

Rupal Javiya