0

The following jquery code works, but if I change td.remove() to td.empty() I get the error message: Uncaught TypeError: td.empty is not a function

I want to empty the contents of the td rather than remove the td so I can potentially put some different text in there later. How can I do that?

$('.msg-delete').click(function () {
    var id = this.getAttribute("data-id");
    var td = this.closest("td");
    if (id) {
        $.ajax({
            type: 'DELETE',
            url: '/messages/' + id,
            success: function () {
                td.remove();
            },
            error: function (error) {
                console.log(error);
            }
        });
    }
})

The table I am working on looks like this:

<table>
<tbody>
    <tr>
       <td>
            <button type="button" class="close msg-delete" data-id="5">&times;</button>
           <label>From:</label> Joe &nbsp;<label><br/>a test message
         </td>
     </tr>
  </tbody>
  </table>

Note: I also tried changing this.closest("td") to $(this)[0].closest("td") with the same result.

AnneMz
  • 484
  • 1
  • 6
  • 16
  • See [jQuery $(this) vs this](http://stackoverflow.com/questions/1051782/jquery-this-vs-this) – showdev Nov 11 '15 at 21:18
  • thanks @showdev I actually read that but perhaps my remaining confusion is around I seem to need $(this).closest("td") but $(this)[0].getAttribute("data-id") why do I need [0] on getAttribute but not closest? – AnneMz Nov 11 '15 at 21:38
  • [`getAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute) is a native JavaScript method, while [`closest()`](https://api.jquery.com/closest/) is a jQuery method. – showdev Nov 11 '15 at 21:50
  • aha! thanks @showdev – AnneMz Nov 11 '15 at 21:57

1 Answers1

1

closest() and empty() are both jQuery methods so you need:

var td = $(this).closest("td") 

And

td.empty();
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Perhaps my confusion is around I seem to need $(this).closest("td") but $(this)[0].getAttribute("data-id") why do I need [0] on getAttribute but not closest? – AnneMz Nov 11 '15 at 21:35
  • `$(this)[0]` is the same as `this` ... it is the actual dom element, not a jQuery object. You are mixing jQuery and native methods. Better to stick to one or the other like `var id = $(this).data("id");` – charlietfl Nov 11 '15 at 22:39