jQuery - Can't use replaceWith() function - Cannot read property 'createDocumentFragment' of undefined

117 Views Asked by At

after a call with Axios, I want to replace the current item with a new one. I proceed like this:

var replacedElement = "<span class='float-right' aria-hidden='true'>" +
            "<i class='fas fa-check icon-color'></i>" +
            "</span>";

        axios.post(url).then(function (response) {
           $(this).replaceWith($.parseHTML(replacedElement));
        });

But I have the following error : Uncaught (in promise) TypeError: Cannot read property 'createDocumentFragment' of undefined

My $(this) references a span element :

enter image description here

So I don't understand why I have this error

1

There are 1 best solutions below

0
nick zoum On BEST ANSWER

This seems to be a this related error and not a jQuery one. You can check how this gets calculated on this other answer I've posted.

There are 3 simple ways to solve your problem.

  1. Storing this in a variable (a common name is self)
var self = this;
axios.post(url).then(function(response) {
  $(self).replaceWith($.parseHTML(replacedElement));
});
  1. Using Function#bind to make sure this won't change
axios.post(url).then((function(response) {
  $(this).replaceWith($.parseHTML(replacedElement));
}).bind(this));
  1. Using Arrow Functions that don't alter the arguments and this (won't work in older browsers)
axios.post(url).then((response) => $(this).replaceWith($.parseHTML(replacedElement)));