Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent div id of second javascript? [closed]

I have a div which is like this:

<div id="mainDiv">
<script>
javascript here...
</script>
</div>

I basically want to get the ID of the div it is inside.

I have tried using jQuery and classic javascript to do this but it keeps returning undefined.

Does anyone have any idea's? Thanks

like image 478
realtek Avatar asked May 25 '26 21:05

realtek


1 Answers

Since broswer read the code from up to down, you can do this:

Vanilla JS

var scriptTags = document.getElementsByTagName('script');
var id = scriptTags[scriptTags.length - 1].parentNode.id;

jQuery

var id = $('script').last().parent().prop('id');

when it will read this code, the last script tag is the one the browser is reading.

Here's a fiddle : http://jsfiddle.net/nb234/

like image 152
Karl-André Gagnon Avatar answered May 28 '26 09:05

Karl-André Gagnon