Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a.nodeName is undefined Jquery error

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>
like image 293
Barney Avatar asked Jan 11 '12 09:01

Barney


3 Answers

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>
like image 185
Rory McCrossan Avatar answered Oct 03 '22 10:10

Rory McCrossan


Try:

$(document).ready(function() {
    $("img").click(function() {
        $(this).closest('tr').fadeOut(400, function(){
            $(this).remove();
        });
    });
});
like image 26
Sudhir Bastakoti Avatar answered Oct 03 '22 09:10

Sudhir Bastakoti


I encountered a similar issue and the solution was to switch from an arrow function to a traditional named function. Sometimes old is gold but I'm sure there is a root cause somewhere.

This didn't work:

$(document).ready(() => {
  $('#client_id').change(() => {
    const clientId = $(this).val();
    console.log(clientId);
  });
});

The console print out was the error:

TypeError: i.nodeName is undefined

On further investigation it turned out '$(this)' was calling the window object rather than the select element. (As pointed out by Rory above: https://stackoverflow.com/a/8817193/5925104)

This worked. A value was printed out to the console.

$(document).ready(() => {
  $('#client_id').change(function changeClient() {
    const clientId = $(this).val();
    console.log(clientId);
  });
});

UPDATE

This is one of the limitations of arrow functions. And I quote, "Does not have its own bindings to this or super, and should not be used as methods." Since the jQuery method above uses 'this' context, arrow functions should be avoided in such a case and a traditional function expression used instead. Here's the documentation to support this.

like image 30
Raymond Wachaga Avatar answered Oct 03 '22 09:10

Raymond Wachaga