Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda