Search code examples
javascriptbookmarklet

How do you delete every single element from a page in JavaScript?


I am trying to make a bookmarklet that "explodes" your computer after a set period of time. I have everything I need except that I want it to delete everything from the page so that it looks like they have been destroyed from the explosion. This is my current code:

javascript: (() => {
  let rando = Math.floor(Math.random() * 10);

  function explode() {
    alert('BOOM!');
    document.body.style.backgroundColor = 'red';
  }

  alert(`Your computer will explode in ${rando} seconds.`);
  setTimeout(explode, rando * 1000);
})();

I want to delete all the elements from the page inside of the explode function so that it deletes everything then makes the screen red.


Solution

  • As Pointy pointed out in the comments, you can simply overwrite everything in the <body> tag with document.body.innerHTML = "";. Also, it is possible that rando is floored to 0 seconds and the code runs immediately, which is probably not what you want, so I'd use Math.ceil() instead:

    (() => {
      let rando = Math.ceil(Math.random() * 10);
    
      function explode() {
        alert('BOOM!');
        document.body.innerHTML = "";
        document.body.style.backgroundColor = 'red';
      }
    
      alert(`Your computer will explode in ${rando} seconds.`);
      setTimeout(explode, rando * 1000);
    })();
    <p>
      test content
    </p>

    Because you tagged your question with , here's the same code as a bookmarklet:

    javascript:(()=>{let rando=Math.floor(Math.random()*10);function explode(){alert('BOOM!');document.body.innerHTML="";document.body.style.backgroundColor='red'}alert(`Your computer will explode in ${ rando } seconds.`);setTimeout(explode,rando*1000)})();