tags:

views:

439

answers:

3

I am trying to figure out the location of the script tag the current javascript is running in. These are dynamically generated tags.... code snippet:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>where am i?</title>
  <script type="text/javascript" charset="utf-8">
    function byId(id) {
      return document.getElementById(id);
    }

    function create_script(el, code) {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.text = code;
      el.appendChild(script);
    }
  </script>
</head>
<body>
  <div id="find_me_please"></div>
  <script>
    create_script(byId("find_me_please"), "alert('where is this code located?');");
  </script>
</body>
</html>

Thanks!

UPDATE:

So I do not think my initial example was as clear as I had thought.

What is really going on is that I need to determine from inside a src'd, dynamically inserted javascript file where it is located in the DOM.

+4  A: 

You could give the script an id tag, like this dude does...

sammich
wow, awesome stuff! only problem is that I will not be able to know the id from inside the code... (usually it is src'd)... I /can/ have code inside the src'd js script, but without that knowledge... unfortunately.
Matt Secoske
+2  A: 

You can use document.write to create a dummy DOM object and use parentNode to escape out. For example:

<script>
(function(r) {
  document.write('<span id="'+r+'"></span>');
  window.setTimeout(function() {
    var here_i_am = document.getElementById(r).parentNode;
    ... continue processing here ...
  });
})('id_' + (Math.random()+'').replace('.','_'));
</script>

This assumes you don't actually have control of the <script> tag itself, such as when it's inside a <script src="where_am_i.js"></script> - if you do have control of the <script> tag, simply put an ID on it, as in:

<script id="here_i_am">...</script>
geocar
cannot do document.write ... in fact that is part of the reason for asking :)
Matt Secoske
Why can't you do document.write?
geocar
my js is inserted after the dom has completed
Matt Secoske
Then you already *know* where the JS is being inserted.
geocar
A: 

If you are just running this on page load, this works

<script>
  var allScripts = document.getElementsByTagName('script');
  var thisScript = allScripts[allScripts.length];
  alert(thisScript);
</script>
scunliffe
allScript.length-1, surely.
bobince
yup, but unfortunately I am not running it onload... coming up with a better explanation of what I'm trying to do :)Thanks though, useful for many other situations!
Matt Secoske