0

For example,

<body>
    <div id="cant_set_id" class="cant_set_class">
    </div>
    <div>
        <script id="cant_set_id">
            thisDivElement = // How to get a handle to this parent div
        </script>
    </div>
</body>

I feel I'm missing fundamental bit of JavaScript knowledge here; however, I've never needed this till now. How can a script in that div, get a handle to the div when neither have id's and the div+script may be located anywhere in the DOM?

  • I'd just use an ID and access it later using that. At the time that script is being executed, the DOM element for the `div` in question isn't even fully constructed, trying to access it just feels wrong. – millimoose Feb 13 '13 at 20:57
  • I guess you could inspect the DOM in your script, find the last div leaf, and dynamically add it an id or class you could use later on. I'm afraid that's just random thoughts. I don't know if it would work. – jbl Feb 13 '13 at 21:10
  • Thanks all. Someone pointed me to the duplicate problem. It describes how to leverage the behavior of JavaScript to get a handle to the last run/current script element, which makes getting at it's parent simple. –  Feb 13 '13 at 22:47

1 Answers1

1

There are several ways to do this:

  1. Put an id on the script tag and then look up that id and its parent.
  2. Use document.write() from within the script to write a div with a known id and then look for that.
  3. Search for the script tags in the document and find the one with an appropriate .src property.
  4. 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/

jfriend00
  • 683,504
  • 96
  • 985
  • 979