2

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();
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

1

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();
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    huh, all methods seemed to work... but why should I be using the .data() instead of the .attr("data-value") if they both work fine? – Dimitri Bostrovich Mar 26 '20 at 16:15
  • [This answer](https://stackoverflow.com/a/7262427/519413) explains it better than I ever could, but the short answer is performance. – Rory McCrossan Mar 26 '20 at 16:30
  • 1
    thanks for the answer and link. something i found interesting, though I know its not part of the question. When I remove one block, it works perfectly. However, when I try to remove more than one, it stops working after the first one. However there is an ajax request that follows the click function. Even though it doesnt appear to be removed. It is in the server. Have any idea why its not removing the other divs? – Dimitri Bostrovich Mar 26 '20 at 18:43
  • 1
    I know you suggest not to use the `.attr("data-value")` approach, but when swapping out your `.data('value')` with `.attr("data-value")` in each location, for both suggestions, it started to work. not exactly sure why, or if it is bad, but I will use this method for now – Dimitri Bostrovich Mar 26 '20 at 18:53