Reputation: 31
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?
Upvotes: 0
Views: 103
Reputation: 63524
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>
Upvotes: 1