Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  153] [ 5]  / answers: 1 / hits: 20096  / 13 Years ago, thu, february 9, 2012, 12:00:00

How can I find out what the element is that a <script> sits in?

As an example, let's 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 what element we're in?

So I want to write, for instance 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 it, but I have the feeling that wouldn't be necessary. The browser knows where we are, otherwise it couldn't even do the document.write!



So, suggestions? I searched, but couldn't find it. Is it so simple that I'm overlooking the obvious?


More From » dom

 Answers
44

Script are executed in the order of appearance in the document. The contents of a script tag are evaluated on encounter, so, the last <script> element is always the current one.



Code:



<div>
<script>
var scriptTag = document.getElementsByTagName('script');
scriptTag = scriptTag[scriptTag.length - 1];

var parent = scriptTag.parentNode;
</script>
</div>

[#87571] Tuesday, February 7, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryonk

Total Points: 161
Total Questions: 116
Total Answers: 107

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;