How to clone a dynamically created element with jquery?

Asked

Viewed 188 times

1

I need help cloning an already created element dynamically with Jquery and adding +1 in value and element 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 would like to clone is the first 'li', and add just below.

  • $('.Nameopleols > li:first-Child'). clone(). appendTo('.Nameopleols'); $('.Nameopleols > li:last-Child > input'). attr('id', 'Newid'). val('XYZ');

  • It worked, only in case I’ll have other Divs with the same elements then how do I clone only in the div that I am?

1 answer

1

Well, if I was going to need a constant html and change only a few values, I would use a "template" or static 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 mounting your li no js same, so no problem assign to a variable to then 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>

Could use:

var cloneDaDiv = $(".div-para-clonar").clone();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.