Search code examples
javascriptdocumenterase

Javascript | How to erase anything (divs, p's, a's, ...) which has not class ".destroy"?


How can I make this work with pure Javascript? Erase everything (divs, ps, as, spans, imgs, ...) in the Body section of a HTML document which has NOT the class"destroy".

PS.: Pure Javascript means: No JQuery or other frameworks..


Solution

  • You could walk the DOM recursively and check every node for its class. Something like this

    function walk_the_DOM(node) {
        if (node.className && (node.className.indexOf("destroy")>-1)) {
            node.parentNode.removeChild(node);
        } else {
          node = node.firstChild;
          while (node) {
           walk_the_DOM(node);
           node = node.nextSibling;
          }
        }
     };
    
    walk_the_DOM(document.body);