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

101
Visualizações
Get Data Attribute from the new HTML Element just added using Jquery

Just added new element in my HTML code using jquery .html() but cannot get the data attribute from this new element.

Ilustration:

<div class="row" id="append">
  <div class="col-12" id="newElement">
    <button>Add new element</button>
  </div>
  <div class="col-md-3 see-id">
    <button data-id="0.901065887770927">Check ID</button>
  </div>
</div>
<script>
  $(document).ready(function(){
    $('.see-id').click(function(){
      alert($(this).data('id'));
    })
    $('#newElement').click(function(){
      var rand = Math.random();
      $('#newElement').after('<div class="col-md-3 see-id"><button data-id="'+rand+'">Check ID</button></div>');
    })
  })
</script>

How to get data attribute from the new element just added using DOM?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Because you're adding new HTML to the document you need to use event delegation to get at the data. Attach the listener to the parent element, in this case .row. But you also need to target the button, so your selector should be .see-id button.

Note: I've separated out the HTML so the query can work better. New buttons were being added before the previous ones in the .row div which could give misleading results when you clicked on them. In this example I use append instead.

$(document).ready(function() {

  $('.row').on('click', '.see-id button', function () {
   const id = $(this).data('id');
   console.log(id);
  });

  $('#newElement').on('click', function () {
    const rand = Math.random();
    $('.row').append(`<div class="col-md-3 see-id"><button data-id="${rand}">Check ID</button></div>`);
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="newElement">
  <button>Add new element</button>
</div>
<div class="row"></div>

about 4 years ago · Juan Pablo Isaza 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