最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to get ID of div javascript is contained within? - Stack Overflow

programmeradmin0浏览0评论

I want to insert javascript inside a div that will retrieve that div's ID, as such:

<div id="example"><script>(retrieve id)</script></div>

And that would hopefully return "example". Sorry if this has been asked before, I did check and couldn't find it. Thanks!

I want to insert javascript inside a div that will retrieve that div's ID, as such:

<div id="example"><script>(retrieve id)</script></div>

And that would hopefully return "example". Sorry if this has been asked before, I did check and couldn't find it. Thanks!

Share Improve this question asked Jan 10, 2013 at 17:26 user1790093user1790093 2012 gold badges3 silver badges8 bronze badges 6
  • 2 Can you explain why you would need such a thing? Looks a lot like you're shooting yourself in the foot here. – Tomalak Commented Jan 10, 2013 at 17:29
  • Just for the purpose of trouble shooting, I have a lot of divs and want to be able to quickly see whether they are all named properly; it'll be quicker than reading through the code and easier to make sure I don't miss anything. – user1790093 Commented Jan 10, 2013 at 17:30
  • ignore @Tomalak... he can't see your feet at all ;-) But yeah... you should just hard code it in the script, the same value you hard code as html (i.e. "example") – musefan Commented Jan 10, 2013 at 17:32
  • 1 See stackoverflow./questions/13866774/… – Salman Arshad Commented Jan 10, 2013 at 17:32
  • 2 Can't you just get all div tags and iterate through the nodeList and console.log ids? – Teemu Commented Jan 10, 2013 at 17:39
 |  Show 1 more ment

2 Answers 2

Reset to default 3

The following will only work when you load the script synchronously and not with async option.

It simply counts the script tags that do exist when it's loaded, assumes that it's currently the last one (that's why async would probably fail) and then it's querying its parent node, which is your div.

<div id="example">
  <script>
    (function () {
        var scripts = document.getElementsByTagName('script'),
            myScript = scripts[scripts.length - 1]

        console.log(myScript.parentNode.getAttribute('id')); 
     })();

</script>

</div>

http://jsfiddle/vy5Z7/1/

Are you able to put an id on the script tag?

<div id="example">
<script id="myScript">
  var myScript = document.getElementById('myScript');
  var myId = myScript.parentNode.id;
  alert(myId);
</script>
</div>

http://jsfiddle/abzLn/

发布评论

评论列表(0)

  1. 暂无评论