2

On async call I am receiving a HTML component which I want to replace with another div.

Here is my main HTML:

<div id="main">
  <H1>Name</h1>
  <div>Content wil reside here</div>
</div>

How can I replace div id="main"child with the response.data HTML response. Is there any possible way to do so?

Here is the async call:

axios.post(url, newState).then(response => {
  console.log(response.data);
}).catch(error => {
  console.log(error);
  console.log(error.response.data);
});

It's returning me a complete div:

<div>
Hi
<p>Hello</p>
</div>
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • 1
    You should be very aware when you use the dynamic html received from some response as it might not be safe. – RajkumarG Oct 12 '20 at 12:05
  • You can refer to this question answer [How to replace div with another div in javascript?](https://stackoverflow.com/questions/37347690/how-to-replace-div-with-another-div-in-javascript). **Warning** Its work when you will know the `id` of the div which coming as a response. – Rabby Oct 12 '20 at 12:53

2 Answers2

0

I suggest you use jQuery to replace the element, using method replaceWith. You can do it this way:

 axios.post(url,newState)
       .then(response => {
           const $recievedHTML = $(response.data);
           $("#main div").replaceWith($recievedHTML);
       })

This will work of course only if the received data is a valid HTML element.

-1

outerHTML will replace the element itself.

JS

var main = document.getElementById('main');
axios.post(url,newState)
  .then(response => {
    main.outerHTML = response;
  })
  .catch(error => {
    main.outerHTML = error;
  });

HTML

<div id="main"></div>
benhatsor
  • 1,863
  • 6
  • 20