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.
<div id="example">
<script>
(function () {
var scripts = document.getElementsByTagName('script'),
myScript = scripts[scripts.length - 1]
console.log(myScript.parentNode.getAttribute('id'));
})();
</script>
</div>
Solution 2:
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>
Post a Comment for "How To Get ID Of Div Javascript Is Contained Within?"