tags:

views:

37

answers:

2

I'm wondering if there is a way to get a handle on the DOM element that contains the script inside it. So if I had:

<script type="text/javascript> var x = ?; </script>

Is there a way that I can assign "x" a reference to the script element that contains "x"?

A: 

There isn't a truly safe way.

The closest you can come is to use getElementsByTagName to get all the scripts, get its length, get the last script element, then work from there.

This can fail if the script is deferred or if the script has been dynamically added to the page before another script element.

David Dorward
A: 

You could include some marker text in the script element, and then (similar to what David said), you can loop through all the script elements in the DOM (using getElementsByTagName or whatever features your library, if you're using one, may have). That should find the element reliably. That would look something like this (live example):

<body>
  <script id='first' type='text/javascript'>
    (function() {
      var x = "MARKER:first";
    })();
  </script>
  <script id='second' type='text/javascript'>
    (function() {
      var x = "MARKER:second";
    })();
  </script>
  <script id='third' type='text/javascript'>
    (function() {
      var x = "MARKER:third";
    })();
  </script>
  <script id='last' type='text/javascript'>
    (function() {
      var scripts, index, script;

      scripts = document.getElementsByTagName("script");
      for (index = 0; index < scripts.length; ++index) {
        script = scripts[index];
        if (script.innerHTML.indexOf("MARKER:second") >= 0
           && script.id !== "last") {
          display("Found MARKER:second in script tag #" + script.id);
        }
      }

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = msg;
        document.body.appendChild(p);
      }
    })();
  </script>
</body>

Note that, like the script above, if you're looking for a script tag marker from within a different script tag, you'll need to handle that. Above it's handled by checking the ID of the script tag, but you can also just break it up in the one you don't want to find, like this (live example):

if (script.innerHTML.indexOf("MARKER:" + "second") >= 0) {
  display("Found MARKER:" + "second in script tag #" + script.id);
}
T.J. Crowder