How to clone a dynamically created element with jquery?

1

I need help cloning an element already dynamically created with Jquery and add +1 in the element's 'value' and 'name'.

else if(valorSelect == 'listaSuspensa'){
$(this).parents(".questionario").find('.divResposta').html(
'<div class="divListaSuspensa">'+
'<ol>'+
'<div class="NomearOpcaoLS">'+

  '<li><input class="w3-
   input w3-left" type="text" name="txtMultiplaEscolha" value="Opção 1" 
   style="width:90%">'+                     
  '<a id="id_ExcluirRespostaLS" class="excluirLS w3-
   right w3-bar-item w3-button w3-right" style="color: grey;"><i 
   class="material-icons">close</i></a></li><br><br>'+

  '<li><a class="AddQtdLS">Adicionar opção</a></li>'+

'</div>'+
'</ol>'+
'</div>'

);

The element I'd like to clone is the first 'li', and add it down below.

    
asked by anonymous 19.06.2017 / 19:30

1 answer

1

Well, if I were to need an html always and change only a few values, I would use a static "template" or html. Something like:

html = '<li>';
html += '<input class="w3-input w3-left" type="text" name="txtMultiplaEscolha" value="!value" style="width:90%">';
html += '<a id="id_ExcluirRespostaLS" class="excluirLS w3-right w3-bar-item w3-button w3-right" style="color: grey;">';
html += '<i class="material-icons">close</i>';
html += '</a>';
html += '</li>';

$(".ul-append").append(html.replace("!value", "Opção 1"));
$(".ul-append").append(html.replace("!value", "Opção 2"));

Because you are already assembling your li in the same js, then, without problem assign to a variable to later use the same structure, no?

But if you wanted to clone an element that would already be rendered, we assume:

<div class='div-para-clonar'><p>Div para clonar </p></div>

You could use:

var cloneDaDiv = $(".div-para-clonar").clone();
    
19.06.2017 / 19:56