How to clone a single element of a class in jquery?

1

Hello! What happens is that I have the following html code that is to create dynamic objects:

<!doctype html>
    <html lang="es-mx">
    <head>
        <style>
        .opcion{
            width: 100%;
            margin: 0px auto 10px auto;
            border-radius: 5px;
            padding: 10px;
            background: rgb(200, 200, 230);
            font-size: 1.2em;
            font-weight: bold;
        }

        </style>
    </head>
    <body>
        <h2>Clonando elementos</h2><br>
        <button type="button" onclick="crearItems()">Presioname</button>
        <div id="elementos">
            <div class="row opcion">
                <div class="opc-contenido" class="media-body">
                    <a class="mt-0">Item 1</a>
                    <p class="mb-0">Elemento</p>
                </div>
            </div>
        </div>
        <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="crossorigin="anonymous"></script>
        <script>
        function crearItems()
        {
           $('.opcion').clone().appendTo('#elementos');
        }
</script>
    </body>
</html>

The problem is that as it is a class, because when there is an element, it is copied and inserted, but being two elements with the same class, when clicking again, copy the two and insert them, doing it again copy the 4, and so on until your computer crashes ... But what I want is that only one element is cloned every time I click, NOT ALL. How could that be solved? Thanks

    
asked by Ismael Salas López 22.06.2018 в 20:25
source

1 answer

1

You can use :first of jQuery like this:

<!doctype html>
    <html lang="es-mx">
    <head>
        <style>
        .opcion{
            width: 100%;
            margin: 0px auto 10px auto;
            border-radius: 5px;
            padding: 10px;
            background: rgb(200, 200, 230);
            font-size: 1.2em;
            font-weight: bold;
        }

        </style>
    </head>
    <body>
        <h2>Clonando elementos</h2><br>
        <button type="button" onclick="crearItems()">Presioname</button>
        <div id="elementos">
            <div class="row opcion">
                <div class="opc-contenido" class="media-body">
                    <a class="mt-0">Item 1</a>
                    <p class="mb-0">Elemento</p>
                </div>
            </div>
        </div>
        <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="crossorigin="anonymous"></script>
        <script>
        function crearItems()
        {
           $('.opcion:first').clone().appendTo('#elementos');
        }
</script>
    </body>
</html>
    
answered by 22.06.2018 / 20:27
source