4

I would like to get ID of javascript's container, for ex:

<div id="d_17j_a">
   <script type="text/javascript">
      alert("<ID of javascript's container here>");
      // it will alert: d_17j_a
   </script>
</div>

(ID of div is dynamic)

Thank for any suggestion !

Rong Nguyen
  • 4,143
  • 5
  • 27
  • 53

3 Answers3

4

So scripts are loaded sequentially, so you can get the parent node of a script element through:

var scripts = document.getElementsByTagName('script');
var me = scripts[scripts.length-1];
console.log('parent id', me.parentNode.id);
Jan Jongboom
  • 26,598
  • 9
  • 83
  • 120
3

<script id="FindMe" type="text/javasctipt"> should work just fine using jQuery("#FindMe").parent().id

In pure javascript

document.getElementById("FindMe").parentNode.id

Nomad101
  • 1,688
  • 11
  • 16
2

If you can add an id to your script tag you can grab the parent with Javascript after retrieving the script element.

<div id="d_17j_a">
   <script id="myScript" type="text/javascript">
      var parentId = document.getElementById("myScript").parentNode.id;
      alert(parentId);
      // it will alert: d_17j_a
   </script>
</div>
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189