Home > Net >  Replace body's content by a div's content
Replace body's content by a div's content

Time:12-30

I want to erase the content of the body and replace it by the content of a div that is inside the body. I'm trying to do it but the way I do it makes it impossible: the content of the div is itself erased since I already erased the body. I simplified the structure of the HTML page:

<body>
  <p>whatever</p>
  <div id="remove">
    <p>final result</p>
  </div>
</body>

and here's the desired result:

<body>
  <p>final result</p>
</body>

I think the way I'm trying to resolve the problem is wrong, I think I should replace the body's content by the div's content, not erase the body, but I don't know how to erase the body's content without deleting the body itself.

Do you have any ideas about how to do it? Thank you and have a great day :)

CodePudding user response:

There is not much context to this question, but I would start with something like this. Get the HTML from the div based on the id shown, and use it to replace the contents of the body HTML.

$('body').html($('#remove').html())

CodePudding user response:

In vanilla JS

This is a relatively simple way to do it:

  1. Separate the body into 2 divs
  2. Put the hidden content inside the second div and give it a class of “hidden” This we can style with a display of none so people can’t see it.
  3. Then we create a function that takes the content of the hidden div, and puts it into the first.

Another way to do this.

Store the HTML of the div inside a variable, then set the HTML of the body to whatever is inside the div Then append the div back into the body


<body>
  <div id = “fake_body”>
  </div>
  <div id = “hidden” style = “display: none”>
    <p>Hidden stuff here</p>
  </div>
  <script>
    function change(){
      var divContent = document.querySelector(“#hidden”);
      document.querySelector(“#fake_body”).innerHTML = divContent;
    }
  </script>
</body>

To erase the div from the original content, just change document.querySelector(“#fake_body”) to document.body

This will remove the divs content though. Both of these will work, the second option is simpler

  • Related