Sagar Singh Sagar Singh - 2 years ago 65
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
type: "POST",
url: ",
data: "ids=" + ids,
success: function(data) {
setTimeout(function() {
}, 2000);

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

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download