1

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

eronn
  • 1,690
  • 3
  • 21
  • 53
  • 2
    Have you added a `console.log(this)` inside the `then` function, because I' pretty sure that `this` won't refer to the same object? If that is the issue try storing `this` in a variable like `var self = this` and use `self` instead of `this` inside the `then` function. – nick zoum Dec 22 '20 at 14:12
  • You are right. When I made a `console.log ($(this))`, I did it before calling axios. Well done and thank you! :) – eronn Dec 22 '20 at 14:19
  • 1
    I've added a proper answer, with a couple of solutions and a link for understanding how `this` gets calculated. – nick zoum Dec 22 '20 at 14:45

1 Answers1

1

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)));
nick zoum
  • 7,216
  • 7
  • 36
  • 80