There are several ways to do this:
- Put an id on the script tag and then look up that id and its parent.
- Use
document.write()
from within the script to write a div with a known id and then look for that.
- Search for the script tags in the document and find the one with an appropriate
.src
property.
- Since the scripts are parsed/executed in order (if not defer or async or dynamically inserted), the currently executing script tag is the last one that in the document so far so if you do
document.getElementsByTagName("script")
, the currently executing script tag will be the last one in this list.
Example of option 1:
<body>
<div id="maybe_not" class="probably_not">
</div>
<div>
<script id="myScript">
var parentDiv = document.getElementById("myScript").parentNode;
</script>
</div>
</body>
Working demo of option 1: http://jsfiddle.net/jfriend00/LCuNq/
Example of option 2:
<body>
<div id="maybe_not" class="probably_not">
</div>
<div>
<script>
document.write('<div id="myScriptDiv"></div>');
var parentDiv = document.getElementById("myScriptDiv").parentNode;
</script>
</div>
</body>
Working demo of option 2: http://jsfiddle.net/jfriend00/8YwYN/