Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
jQuery appendTo ignoring last element

I'm trying to append a copy of an element to the bottom of the parent element. It seems to append everything above the last element within the parent. Live example on JSFiddle

var count = 1;

$("#addBtn").click(function(){
  $('#trid1').clone().appendTo('table#exampleTable > tbody');
  count++;
  $('#trid1').last().prop('id', 'trid'+count);
  $('#trid'+count+' > th').html(count);
});
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table class="table" id="exampleTable">
  <thead>
    <tr>
      <th scope="col">c1</th>
    </tr>
  </thead>
  <tbody>
    <tr id="trid1" class="trclass">
      <th scope="row">1</th>
    </tr>
  </tbody>
</table>
<button type="button" id="addBtn">Add</button>

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

I would change the id before appending the new element to the DOM.

Anyway I slightly refactored your code with that strategy in mind and better dealt with the current index every time you click the add button. The latest index gets saved in a data attribute in the table.

$("#addBtn").click(function(){
  const latestIndex = $('#exampleTable').data('latest-index');
  let i = latestIndex+1;
  const newRow = $('#trid1').clone();
  newRow.prop('id', `trid${i}`);
  newRow.data('index', i);
  newRow.text(i);
  newRow.appendTo('table#exampleTable > tbody');
  $('#exampleTable').data('latest-index', i);
});
button{
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="exampleTable" data-latest-index="1">
  <thead>
    <tr>
      <th scope="col">Rows</th>
    </tr>
  </thead>
  <tbody>
    <tr id="trid1" class="trclass">
      <th scope="row">1</th>
    </tr>
  </tbody>
</table>
<button type="button" id="addBtn">Add</button>

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda