April 29, 2011

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

Question by Tomkay

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..

Answer by naivists

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);

Answer by Starx

If you remove everything, you will remove body, head and others too. So to avoid this you can try the following code using Jquery

Try this

$("body").children(':not(.destroy)').remove();

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!