1

Is there a way to get an object or it's id within a script lies using jQuery or something?

For example:

<div id="div1">
  <script type="text/javascript">
     var obj = ?? // this should be the "div1" div
  </script>
</div>

In this example, obj should be equal to "div1" (or the object itself).

Another one:

<p id="paragraph_7">
  <script type="text/javascript">
     var obj = ?? // this should be the "paragraph_7" p
  </script>
</p>

In this example, obj should be equal to "paragraph_7" (or the object itself).

If I give an "id" to the script tag and then get it's parent should work, but is there another way? not always i'm able to know the <script> id.

Thanks in advance.

Phoenix
  • 1,256
  • 2
  • 17
  • 25

2 Answers2

2

Since scripts are executed sequentially, the currently executed script tag is always the last script tag on the page until then. So, to get the script tag, you can do:

var scripts = document.getElementsByTagName( 'script' );
var thisScriptTag = scripts[ scripts.length - 1 ];

You could then use this:

var obj = thisScriptTag.parentNode;


Part of this is from https://stackoverflow.com/a/3326554/1188942
Community
  • 1
  • 1
jeff
  • 8,300
  • 2
  • 31
  • 43
  • Note that this will only work if the code is ran while the page is being parsed. If run in a function, it will always give the last script element on the page when the function was called. – jordanbtucker Aug 09 '12 at 07:22
1

Insert this code and it will work. Basically, by the time you queried for scripts, your currently running script is the last in the list of <scripts> that are currently in the DOM.

<script>
    //protect from the global scope using an immediate function
    (function() {

        //just being verbose
        var scripts, scriptIndex, thisScript, parent;

        scripts = document.getElementsByTagName('script');
        scriptIndex = scripts.length - 1;
        thisScript = scripts[scriptIndex];
        parent = thisScript.parentNode.id;

        //proof that we got the parent is to print the id
        document.write(parent);

    }());​

</script>
Joseph
  • 117,725
  • 30
  • 181
  • 234