最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

How to get id of javascript's container? - Stack Overflow

matteradmin3PV0评论

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 !

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 !

Share Improve this question asked May 2, 2013 at 9:21 Rong NguyenRong Nguyen 4,1895 gold badges30 silver badges53 bronze badges 6
  • do you control the markup? – Kevin Bowersox Commented May 2, 2013 at 9:23
  • see stackoverflow./q/403967/989121 for some suggestions – georg Commented May 2, 2013 at 9:25
  • You should be able to start from here: stackoverflow./q/403967/218196. – Felix Kling Commented May 2, 2013 at 9:25
  • @Kevin Bowersox: i am working with many dynamic html, so i would like to do that. – Rong Nguyen Commented May 2, 2013 at 9:26
  • Are you going to have multiple scripts in a single div? or one div will contain 1 script at most? – painotpi Commented May 2, 2013 at 9:29
 |  Show 1 more ment

3 Answers 3

Reset to default 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);

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

In pure javascript

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

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>
Post a comment

comment list (0)

  1. No comments so far