简体   繁体   中英

How to replace div child element?

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>

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM