5

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.

1 Answer 1

15

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

}
Sign up to request clarification or add additional context in comments.

3 Comments

Damn, I didn't spot that. Thanks!
You can also use for (var i = r.length; i--; ) {
Or use Array.from(r). Thus, the count doesn't change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.