1

Is there a way to get a reference to the container of a Javascript function?

To give an example:

<div>
  <script>
   var thisDiv = ???
   doSomething(thisDiv);
  </script>
</div>

It seems that the this keyword only refers to the containing element when it is triggered by direct event such as onClick(). Otherwise this refers to the containing window element. Is there any equivalent way to get the parent or containing element of a <script> snippet ?

jbx
  • 21,365
  • 18
  • 90
  • 144
  • 2
    Related: [How may I reference the script tag that loaded the currently-executing script?](http://stackoverflow.com/q/403967/218196). FYI, elements don't create *scope*. There is only global scope and function scope. A script element doesn't create scope. – Felix Kling Oct 12 '14 at 21:28
  • @FelixKling: Thanks. I just used 'scope' for the lack of a better word. I will change the title to clear any ambiguity. – jbx Oct 13 '14 at 00:09

1 Answers1

1

There is no completely reliably approach. The closest you can come is to find the last script element in the DOM (with document.getElementsByTagName) and then navigate from there (parentNode et al).

That can break if the script element was inserted dynamically or used defer or async.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    If possible you're better off `id`ing the divs that contain the scripts – Jared Smith Oct 12 '14 at 21:28
  • What if I combine the `parentNode` of your solution, with a solution in the link @FelixKling suggested, something like: `var thisDiv = document.currentScript.parentNode;`. Would that work? – jbx Oct 13 '14 at 00:15