Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all script elements using JS

Tags:

javascript

I am trying to remove all script elements from a HTML page. But for some reason, I can only remove about half of them using the below:

function t(){

   var r = document.getElementsByTagName('script');

    for (var i = 0; i < r.length; i++) {

        if(r[i].getAttribute('id') != 'a'){

            r[i].parentNode.removeChild(r[i]);

        }

    }

}

I have that if condition so that I don't remove the executing script.

I am essentially trying to create a dynamic Javascript dis-abler for my selenium tests.

like image 312
Abs Avatar asked Oct 28 '11 18:10

Abs


People also ask

How do I remove a script tag dynamically?

Dynamically removing an external JavaScript or CSS file To remove an external JavaScript or CSS file from a page, the key is to hunt them down first by traversing the DOM, then call DOM's removeChild() method to do the hit job.

How do I remove a script in HTML?

Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

What does the remove () function do in JavaScript?

The remove() method is used to remove an option from a drop-down list. Tip: To add an option to a drop-down list, use the add() method.

How do I remove a script?

To remove a script from an applicationClick the Resources folder, right-click the script, and then click Remove.


1 Answers

Loop in reverse, the count is changing when you start removing nodes.

var r = document.getElementsByTagName('script');

for (var i = (r.length-1); i >= 0; i--) {

    if(r[i].getAttribute('id') != 'a'){
        r[i].parentNode.removeChild(r[i]);
    }

}
like image 91
Jason Harwig Avatar answered Oct 12 '22 19:10

Jason Harwig