Home > database >  how to append again to the position where I removed it?
how to append again to the position where I removed it?

Time:10-07

For example: here is to append between two paragraphs.

I want to keep it always appending where it was removed.

<p>Paragraph 1</p>
<div id="content">
  <h1>Content</h1>
</div>
<p>Paragarph 2</p>

function hide(){
  content.remove();
}

function show(){
  content.appendxxx();
}

CodePudding user response:

What you can do is insert a comment placeholder to keep the place and use it when you want to put the element back.

let placeholder = document.createComment("placeholder");
let content = document.getElementById("content");

function hide(){
  if (content.parentElement) {
    content.parentElement.replaceChild(placeholder, content);
  }
}

function show(){
  if (placeholder.parentElement) {
    placeholder.parentElement.replaceChild(content, placeholder);
  }
}
<p>Paragraph 1</p>
<div id="content">
  <h1>Content</h1>
</div>
<p>Paragarph 2</p>

<button onclick="hide();">Hide</buton>
<button onclick="show();">Show</buton>

  • Related