What is the current element in javascript?

How can I find out that an element is what <script> sits in?
As an example, take this

 <div> <script type="text/javascript"> var time = new Date(), hrs = time.getHours(), min = time.getMinutes(); document.write('It is '+hrs+":"+(min<10?'0':'')+min); </script> </div> 

Then, if I want to change this to something more modern, how can I find out which element we are in?
Therefore, I want to write, for example, in jQuery

 $(thisdiv).html('It is '+hrs+":"+(min<10?'0':'')+min); 

but how do i get thisdiv ?
Yes, I know, I can put an ID on him, but I have the feeling that it would not be necessary. The browser knows where we are, otherwise it could not even have done document.write!

So suggestions? I searched, but could not find it. Is it that simple that I don't notice the obvious?

+9
javascript dom this
Feb 09 '12 at 11:11
source share
4 answers

Scripts are executed in the order they appear in the document. The content of the script tag is evaluated at the meeting, so the last <script> element is always the current one.

the code:

 <div> <script> var scriptTag = document.getElementsByTagName('script'); scriptTag = scriptTag[scriptTag.length - 1]; var parent = scriptTag.parentNode; </script> </div> 
+20
Feb 09 '12 at 11:25
source share

Firefox:

 document.currentScript.parentElement 

Chrome:

 document.scripts.length 
+1
09 Feb '12 at 11:29
source share
 $('script#some_id').parent().html('blah blah'); 
0
Feb 09 '12 at 11:15
source share

try it

 <div id="mydiv"> <script type="text/javascript"> var time = new Date(), hrs = time.getHours(), min = time.getMinutes(); document.getElementById('mydiv').innerHTML = 'It is '+hrs+":"+(min<10?'0':'')+min; </script> </div> 
0
Feb 09 '12 at 11:23
source share



All Articles