views:

42

answers:

2

Hi folks,

When sites give you some JavaScript that you paste into a web page to have content inserted at that position, how does the script determine its current position in the DOM? Without using document.write?

Thanks,

Nick

A: 

I don't see why such scripts would care about their location in the DOM, but I guess it's possible to determine. Maybe use something like document.scripts to start your search.

Assaf Lavie
I don't see the document.scripts in the Mozilla reference:https://developer.mozilla.org/en/DOM/documentSo I'm guessing that's an IE-only thing? Could be wrong though, I'm running Chrome and don't feel like checking! :) Thanks though.
Nick Spacek
It's an IE extension from way back, that's also available on WebKit and Opera. Although since it doesn't give you anything that `getElementsByTagName` doesn't already do, it's never really seen much use.
bobince
+1  A: 

At script inclusion time, it's certain that the last <script> in the page will be the current one; the rest of the page hasn't been parsed yet. So:

<script type="text/javascript">
    var scripts= document.getElementsByTagName('script');
    var this_script= scripts[scripts.length-1];

    // Something that happens later...
    //
    setTimeout(function() {
        var div= document.createElement('div');
        div.appendChild(document.createTextNode('Hello!'));
        this_script.parentNode.insertBefore(div, this_script);
    }, 5000);
</script>

This holds true as long as the script tag doesn't use defer, or HTML5's async.

bobince
Didn't realize that it would work that way, but makes perfect sense, thanks!
Nick Spacek