Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

I'm teaching myself AJAX to AJAXify my site. In my template, I have the following JS code to get some JSON data from a view then append the data to a div.

function filter(type) {
  $.getJSON(
    '/activity_stream/global-activity-stream/', 
    {xhr: "true", filter: type}, 
    function(data) {
      $('.mainContent').children().remove();
      $(data).appendTo('.mainContent');
    });
  }

  $(".btn").click(function () { 
    filter("recent"); 
  });
}

I think my view is returning proper JSON but now data is not being added to the .mainContent div.

It gives this error:

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined.


Solution 1:

Make sure you're passing a selector to jQuery, not some form of data:

$( '.my-selector' )

not:

$( [ 'my-data' ] )

Solution 2:

I had a similar issue. I was using jQuery.map but I forgot to use jQuery.map(...).get() at the end to work with a normal array.

Solution 3:

The same issue came up for me inside of $elms.each().

Because:

  1. the function you pass to .each(Function) exposes (at least) two arguments; the first being the index and the second being the element in the current element in the list, and
  2. because other similar looping methods give current the element in the array before the index

you may be tempted to do this:

$elms.each((item) => $(item).addClass('wrong'));

When this is what you need:

$elms.each((index, item) => $(item).addClass('wrong'));