0

I've looked at these answers but they all talk about (click) events:
Jquery: Select the element that called the function
Getting the ID of the element that fired an event
Get information of element that called function with jQuery

But what if there is no event that triggers the code? What if the script is already sitting inside the DOM element on page load like this:

<div>
  <script>drawChip()</script>
</div>

How would I get a reference to the div element that calls this script using jQuery or Javascript? I've tried this but that didn't work.

Community
  • 1
  • 1
abc123
  • 8,043
  • 7
  • 49
  • 80
  • you could give the div an id – Kevin B Jun 27 '13 at 17:27
  • 2
    @MarcB no it wouldn't. – Pointy Jun 27 '13 at 17:28
  • @pointy: yeah. fingers running ahead of brain. realized it wasn't an onclick handler. – Marc B Jun 27 '13 at 17:28
  • 1
    The quick and easy answer: Don't put your script there! There's no good reason to. Put all your scripts just inside the closing body tag. Place the method within a DOM-ready wrapper and target the div with the appropriate selectors. – Derek Henderson Jun 27 '13 at 17:29
  • There is no convenient way to get it automatically like event.target.id. You can pass the element id as parameter to the drawChip function.\ – MAK Ripon Jun 27 '13 at 17:31
  • @DerekHenderson Thanks, your comment made me realize I need to change the way I'm implementing. – abc123 Jun 27 '13 at 17:46

3 Answers3

2

It's not really accurate to say that the <div> "calls" the script. The script is just sitting there and happens to be inside the <div> element, but that fact is uninteresting to the JavaScript runtime.

What you can do is something like this:

<div>
  <script id='script1234'>
    var parentElement = document.getElementById('script1234').parentNode;
    drawChip(parentElement);
  </script>
</div>
Pointy
  • 405,095
  • 59
  • 585
  • 614
0

Try this instead::

var scriptDIVs = $("div").has("script")

Hope this will help !!

Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32
0

Try something like:

<div id="myDiv">
  <script>drawChip(document.getElementById("myDiv") );</script>
</div>
bitfiddler
  • 2,095
  • 1
  • 12
  • 11