Remove all content using pure JS

前端 未结 9 2211
南方客
南方客 2020-12-03 09:56

I\'m looking for a way to remove the entire content of a web page using pure Javascript -- no libraries.

I tried:

document.documentElement.innerHTML          


        
相关标签:
9条回答
  • 2020-12-03 10:40

    REMOVE EVERYTHING BUT --- !DOCTYPE html ---

    var l = document.childNodes.length;    
    while (l > 1) { var i = document.childNodes[1]; document.removeChild(i); l--; }
    

    TESTED ON FIREFOX WEB INSPECTOR - childNodes[1] IS --- !DOCTYPE html ---

    0 讨论(0)
  • 2020-12-03 10:43

    I believe this will do it

    document.clear()  //deprecated
    
    window.location = "about:blank"  //this clears out everything
    
    0 讨论(0)
  • 2020-12-03 10:45

    I think a browser rightfully assumes a page with content-type text/html will always be a web page - so whilst you may do something like...

    document.body.innerHTML = '';
    

    It will still have some HTML hanging around.

    You could try...

    document.documentElement.innerHTML = '';
    

    ...which left me with <html></html>.

    Yi Jiang did suggest something clever.

    window.location = 'about:blank';
    

    This will take you to a blank page - an internal mechanism provided by most browsers I believe.

    I think however the best solution is to use document.open() which will clear the screen.

    0 讨论(0)
  • 2020-12-03 10:48
    var i = document.childNodes.length - 1;
    
    while (i >= 0) {
      console.log(document.childNodes[i]);
      document.removeChild(document.childNodes[i--]);
    }
    

    Removes everything (doctype also) on FF 3.6, Chrome 3.195, and Safari 4.0. IE8 breaks since the child wants to remove its parent.


    Revisiting a while later, could also be done like this:

    while (document.firstChild) {
      document.removeChild(document.firstChild);
    }
    
    0 讨论(0)
  • 2020-12-03 10:52

    According to Dotoro's article on the document.clear method, they (since it's deprecated) recommend calling document.open instead, which clears the page, since it starts a new stream.

    This way, you avoid the nasty about:blank hack.

    0 讨论(0)
  • 2020-12-03 10:55

    I believe this will still leave the doctype node hanging around, but:

    document.documentElement.remove()

    or the equivalent

    document.getElementsByTagName("html")[0].remove()

    0 讨论(0)
提交回复
热议问题