Getting the <script> element reference via JS

E

Eli

Hello,

I want to get a reference to the <script> element (DOM) from the JS
code it contains.

e.g:
<script type="text/javascript">
var scriptElem = ???
</script>

scriptElem should refer to the <script> element that contains it.

-thanks, Eli
 
M

Martin Honnen

Eli said:
<script type="text/javascript">
var scriptElem = ???
</script>

scriptElem should refer to the <script> element that contains it.

With text/html documents it should work to do
<script type="text/javascript">
var scripts = document.getElementsByTagName('script');
var scriptElem = scripts[scripts.length];
</script>
assuming the script is inline as above and the browser does incremental
parsing and script execution.

With application/xhtml+xml at least Mozilla is known to parse the
complete document first so that approach will not work (before Firefox
3.0 comes out).
 
R

Richard Cornford

Martin said:
Eli said:
<script type="text/javascript">
var scriptElem = ???
</script>

scriptElem should refer to the <script> element that
contains it.

With text/html documents it should work to do
<script type="text/javascript">
var scripts = document.getElementsByTagName('script');
var scriptElem = scripts[scripts.length];

var scriptElem = scripts[(scripts.length - 1)];

(zero based indexing on NodeLists)
</script>
assuming the script is inline as above and the browser does
incremental parsing and script execution.
<snip>

So absolutely never include an explicit DEFER attribute on the SCRIPT
element, as that can be expected to provoke that issue where it may not
exist otherwise.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,157
Messages
2,570,879
Members
47,413
Latest member
KeiraLight

Latest Threads

Top