3

Not Looking for a Use Framework XXX Answer

This question is not intended for finding a practical solution via a framework. Answering with use framework XXX, or this is so easy in framework XXX, or why not use this framework XXX??? doesn't answer the question.

I have a function meant to run after a page has been loaded: performShim. This function iterates over all elements in the DOM that are span tags, checks if they have a className of shim and if so, calls shim passing to it a reference of the matched element.

My goal was to prepend another span that contains an iframe to the element that is passed to shim.

With the code I wrote so far, I am able to append to the element's parent just fine. However, if I comment out the append line and instead try the prepend line the browser hangs in presumably an infinite-loop.

It's not readily obvious to me why this is the case.

function shim( element ) {      
    var iframe = document.createElement('iframe');
    iframe.setAttribute( 'frameborder', '0' );
    iframe.setAttribute( 'scrolling', 'no' );
    iframe.setAttribute( 'align', 'bottom' );
    iframe.setAttribute( 'marginheight', '0' );
    iframe.setAttribute( 'marginwidth', '0' );
    iframe.setAttribute( 'src', "javascript:'';" ); 

    var span = document.createElement('span');
    span.appendChild(iframe);


    //element.parentNode.insertBefore(span,element); //causes infinite loop?

    element.parentNode.appendChild(span); //this line works OK

    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'inline';
    var width = element.offsetWidth;
    var height = element.offsetHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility;

    iframe.style.width = (width-6) + 'px';
    iframe.style.height = (height-6) + 'px';

}   

function performShim() {
    var children = document.getElementsByTagName("span");   
    for( var i = 0; i < children.length; i++ ) {
        if( children[i].className == "shim" ) {
            shim(children[i]);  
        }
    }
} 
user17753
  • 3,083
  • 9
  • 35
  • 73
  • `This question is not intended for finding a practical solution ` Then it's in the wrong place. – Lightness Races in Orbit Mar 14 '12 at 20:07
  • 2
    @LightnessRacesinOrbit: You overlooked *[...] via a framework*, which is a perfectly valid demand. – Felix Kling Mar 14 '12 at 20:16
  • Sorry, the question was meant for better understanding of DOM and DOM related pure javascript functions, not a better understanding of how frameworks make your life easier. I'm quite satisfied with the answers given. – user17753 Mar 14 '12 at 20:24
  • @Felix: You overlooked my epic humour – Lightness Races in Orbit Mar 15 '12 at 00:57
  • 1
    @LightnessRacesinOrbit: Maybe my humour detection was blinded by the tiny close vote which seemed to be correlated to your comment. Apologies and no hard feelings ;) – Felix Kling Mar 15 '12 at 01:37
  • I had to preface this question, because all too often I see questions closed or promptly dismissed with a line of jQuery without any actual understanding happening. – user17753 Mar 15 '12 at 15:47
  • Just for reference, this is the exact opposite problem, so to speak, as [Why is this while loop infinite? JavaScript appendChild](/q/13348976/4642212), where a _non-live_ list caused an infinite loop. – Sebastian Simon Jul 02 '21 at 12:50

1 Answers1

8

A NodeList (such as the one returned by document.getElementsByTagName) is typically a live list -- changes you make to the DOM show up in it as well. So each time you add a span before the current one, you're extending the list by one element and moving the current element over by one, and the next iteration puts you right back at the node you just finished.

You have a couple of easy workarounds for that...

  • Bump the counter when you add a node. (Ugly, and if you ever end up adding something instead of a span, you'll end up skipping nodes and it won't be obvious why.)

  • Copy the list to an array and iterate over the array. You could do this with something like
    children = [].slice.call(children, 0); (more common) or
    children = Array.apply(window, children);.

  • Use document.querySelectorAll, which returns you a NodeList that's not live. (And even if it were live, in this case you could select 'span.shim' and the inserted spans wouldn't show up in it anyway.)

  • Iterate backwards (from children.length - 1 to 0).

cHao
  • 84,970
  • 20
  • 145
  • 172
  • 2
    +1. *the next iteration puts you right back at the node you just finished* That's the important part. Appending is "fine" (in this case) because in the next iteration you will be processing an other node and eventually you will run out of `span` nodes with class `shim`. But if the generated `span`s were also assigned the `shim` class, it would generate an infinite loop as well. – Felix Kling Mar 14 '12 at 20:08
  • So in `performShim` is the variable `children` just a reference to a live list? If that's the case, why does appending a `span` work just fine, but prepending doesn't? – user17753 Mar 14 '12 at 20:08
  • 2
    @user1169578: See my comment. Regarding prepending, consider having the nodes `a, b`. Your loop variable is `i = 0`. Now you processing `a` and prepending node `c`. The result is `c, a, b`. Your loop variable advances to `i = 1`, which is again node `a`... etc. If you append instead, your list might look like `a, b, c` and once you are processing `c` you won't append any nodes anymore, because `c` has no class `shim`. – Felix Kling Mar 14 '12 at 20:09
  • 1
    If you use `.querySelectorAll()` you can select by class so (in this case) it doesn't matter if the return is live or not. For the existing code that selects all spans you could just iterate through the loop backwards. – nnnnnn Mar 14 '12 at 20:19
  • Thanks, I guess it's a subtle point that the collection retrieved via functions such as `getElementsByTagName` is a _live_ _collection_. I opted for the copying of the initial collection to an array and iterating over the array. Thanks everyone for explaining this subtle, but very important distinction. @Felix King: Your description is very keen, I understand everything now. – user17753 Mar 14 '12 at 20:21
  • @nnnnnn: I was just adding 'iterate backwards'... :) Good point about qSA though. – cHao Mar 14 '12 at 20:22