Skip to content Skip to sidebar Skip to footer

How To Get Id Of Div Javascript Is Contained Within?

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

Solution 1:

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.

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

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

</script></div>

http://jsfiddle.net/vy5Z7/1/

Solution 2:

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

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

http://jsfiddle.net/abzLn/

Post a Comment for "How To Get Id Of Div Javascript Is Contained Within?"