javascript - If i have a script inside a div, how do i get the id of that particular div? <br> -
if have script inside div, how id of particular div?
(so can below, varying div id's):
<div id="chart_div1" class ="googlepie"> <script type="text/javascript"> drawchart('chart_div1'); </script> </div>
[edit]:
have 2 html views when 1 view's button clicked second view shown.
some javascript reconstructs html this, , wanted charts shown on second view, have click event handling this.
strangely, have managed load particular chart in particular div (of multiple repeated), above, putting script calls drawchart() in div itself. reason couldn't relocate script more comfortable position have suggested. also, no matter suggested methods fetch parents div 'id' tried, kept getting 'undefined container' error.
for example didnt work me:
<div class ="googlepie" id="chart_div1" style ="position:absolute; top: -8%; left:63%;"> <script type="text/javascript" class ="chartscript" id="bakegooglepie"> // drawchart($('.chartscript').parent().attr('id')); // didnt work // drawchart($('#bakegooglepie').parent().attr('id')); // neither did // var parentelementid = $(document.body.lastchild).closest('div').id; // drawchart(parentelementid); // didnt either drawchart('chart_div1'); // did </script>
for reason (particular) solution construct ids , call them in drawchart instead of getting id javascript.
however, have chosen answer original question 1 else seems work , should work others.
note: others have suggested in situations shouldn't need parent id question supposes.
try (jquery):
<div id="chart_div1" class ="googlepie" style ="position:absolute; top: -4%; left:68%;"> <script type="text/javascript"> var parentelement = $(document.body.lastchild).closest('div'); drawchart(parentelement); </script> </div>
or (basic javascript):
<div id="chart_div1" class ="googlepie" style ="position:absolute; top: -4%; left:68%;"> <script type="text/javascript"> var scripttag = document.scripts[document.scripts.length - 1]; var parenttag = scripttag.parentnode; drawchart(parenttag.id); </script> </div>
see here more details: how select parent of <script> element
although answers question on how achieve it, believe not best approach. should place javascript code @ end of html document , use proper selectors target elements.
cheers!