1

I modified the question/answer in the SO post below to remove styles, in forward order.

The question/answer removes scripts in reverse order.

It did not work. However, if I changed it back to reverse order things worked.

My guess, was that if you remove style[0], that style[1] would immediately update to become style[0], in an example w/ only two styles. Hence the loop would fail.

Is this correct?

Is the style array updated near instantaneously as it is modified?

Reference Post

var scripts  = document.getElementsByTagName("script");
for (var i=scripts.length; i--; ){
   (scripts[i]).parentNode.removeChild(scripts[i]);
}
Community
  • 1
  • 1
Smurfette
  • 1,935
  • 2
  • 14
  • 15
  • Absolutely, the HTMLCollection is indeed live, but this is only for some DOM methods (which in itself is rather confusing). – Qantas 94 Heavy Jul 30 '13 at 14:35
  • I think you are correct in your guess, but you have put `style` in the question and `scripts` in the code, which one did you mean to use? Or did you want both like that? – Gray Jul 30 '13 at 14:36
  • possible duplicate of [javascript trying to remove all things with certain tags](http://stackoverflow.com/questions/10889720/javascript-trying-to-remove-all-things-with-certain-tags) – Bergi Jul 30 '13 at 14:54

2 Answers2

2

Your guess is correct; getElementsByTagName returns a live "array" (which is not actually an array, but rather a NodeList or HTMLCollection, depending on browser and version) that reflects subsequent updates to the DOM.

So, you can write:

var styles = document.getElementsByTagName("style");
while (styles.length) {
    styles[0].parentNode.removeChild(styles[0]);
}

That said, there's no reason to prefer this way. Since JavaScript is run in the same thread that paints the UI, the result of removing the styles won't take effect until after the loop is complete, so the order doesn't matter to you.

Useful MDN links:

ruakh
  • 175,680
  • 26
  • 273
  • 307
1

From https://developer.mozilla.org/en-US/docs/Web/API/element.getElementsByTagName:

elements is a live NodeList (but see the note below) of found elements in the order they appear in the subtree. If no elements were found, the NodeList is empty.

So as soon as you remove elements[0], elements[0] is filled with elements[1], thus removing elements[1] (unless there was an elements[2]).

You can do it in "normal" order like this (although it's not as performant due to the repeating test of scripts.length):

var scripts  = document.getElementsByTagName("script");
while (scripts.length) {
    (scripts[0]).parentNode.removeChild(scripts[0]);
}
Brian Cray
  • 1,277
  • 1
  • 7
  • 19