Menu Close

How to clone and remove an element using jQuery?

jQuery clone

To clone an element using jQuery, use the jQuery.clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM. 

Also jQuery.remove() method used to remove the elements.

<html>
    <head>
        <title>jQuery clone method</title>
        <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                $(".remove_btn").click(function(e) {
                    $(this).closest(".copydiv").remove();
                    e.preventDefault();
                });

                $(".clone_btn").click(function() {
                    $(".copydiv:last").clone(true).insertBefore(this);
                });
            });
        </script>
    </head>
    <body>
        <div class="copydiv">
            <div>
                <label>Email ID</label>
                <input type="text" name="name" placeholder="Enter Name">
            </div>
            <a href="#" class="remove_btn">Remove </a>
        </div>
        <button class="clone_btn">Clone</button>
    </body>    
</html> 
If you want to disable remove text from first input field add below style.
<style>
    .copydiv:first-child .remove_btn{
        display:none;
     }
</style> 
Posted in jQuery

You can also read...