Trying to remove an element with data-value equal to a previously created variable?

Viewed 296

When I click on a "trash" button I want to delete the message block. There are multiple message blocks but they all have unique data-values. The id of the targeted block I want to delete is stored in the data-value of .send-message-button.

I tried making a variable that I could pass onto the targeted .messageblock element. I checked with an alert to see if the variable gets the proper number, which it does. However when I alert the whole thing, it gives [object object] (without the .remove, of course).

How can I do this?

var trashid = $(".send-message-button").attr("data-value");
$('.message-block').attr("data-value", trashid).remove();
1 Answers

If you want to retrieve an element using the value of one of its attributes you need to use the attribute selector, not the setter of the attr() method.

There's two main ways to do this. Firstly if the data attribute is present in the DOM then you can use an attribute selector:

var trashid = $(".send-message-button").data('value');
$('.message-block[data-value="' + trashid + '"]').remove();

Alternatively if the data attribute is held in jQuery's cache (as will be the case if you use data() as a getter/setter, as you should be) then you can use filter() instead:

var trashid = $(".send-message-button").data('value');
$('.message-block').filter((i, e) => $(e).data('value') === trashid).remove();
Related