Sagar Singh Sagar Singh - 7 months ago 8
Javascript Question

How to select unique div id & remove it

I fetch posts from database with php while loop, Here is the e.g of HTML code->

<div id="1"> content <button class="btn-primary" data-id="1">button</button></div>
<div id="2">content 2 <button class="btn-primary" data-id="2">button</button></div>


if someone click on first button then div with id=1 should be removed

Here is the jquery code

$(function() {
$("body").on("click", ".btn-primary", function() {
var ids = $(this).data('id'); // get data-id atrribute
var elements = this;
$('#id').remove(); // How can i remove the div by showing each id here
$.ajax({
type: "POST",
url: "https://www.example.com/ajax,
data: "ids=" + ids,
success: function(data) {
setTimeout(function() {
$('.conner').append(data).fadeIn('slow');
}, 2000);
}
});
});
});


How can Get div id dynamically and remove the div on click

Answer

Unless data-id holds several values you can:

var ids = $(this).data('id'); // get data-id atrribute
$('#' + ids).remove();

More simple way - is to remove a button parent:

$( this ).parent().remove();
Comments