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 :
So I don't understand why I have this error
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.
this
in a variable (a common name is self
)var self = this;
axios.post(url).then(function(response) {
$(self).replaceWith($.parseHTML(replacedElement));
});
Function#bind
to make sure this
won't changeaxios.post(url).then((function(response) {
$(this).replaceWith($.parseHTML(replacedElement));
}).bind(this));
arguments
and this
(won't work in older browsers)axios.post(url).then((response) => $(this).replaceWith($.parseHTML(replacedElement)));