Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!