a.nodeName is undefined Jquery error

Barney picture Barney · Jan 11, 2012 · Viewed 18.2k times · Source

a.nodeName is undefined

I've looked this up but the explanations didn't seem at all clear to me.

function deleteThisRow() {
    $(this).closest('tr').fadeOut(400, function(){
        $(this).remove();
    });
}
<tr>
    <td>blah blah blah</td>
    <td>
        <img src="/whatever" onClick="deleteThisRow()">
    </td>
</tr>

Answer

Rory McCrossan picture Rory McCrossan · Jan 11, 2012

The this keyword in your function does not refer to the element which was clicked on. By default it would refer to the highest element in the DOM, which would be the window.

To fix this you can use an unobtrusive event handler, instead of an outdated on* event attribute, as they run under the scope of the element which raised the event. Try this:

$("tr td img").click(deleteThisRow);

function deleteThisRow() {
  $(this).closest('tr').fadeOut(400, function() {
    $(this).remove();
  });
}
img {
  width: 20px;
  height: 20px;
  border: 1px solid #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>blah blah blah 1</td>
    <td><img src="/whatever"></td>
  </tr>
  <tr>
    <td>blah blah blah 2</td>
    <td><img src="/whatever"></td>
  </tr>
  <tr>
    <td>blah blah blah 3</td>
    <td><img src="/whatever"></td>
  </tr>
</table>