3

How can one refer to the script itself as an element of HTML DOM from inside the script using pure javascript?

The purpose of this is to manipulate other elements of HTML DOM relatively to script. Something like <script>this.previousSibling ... this.nextSibling ... </script> .

progmastery
  • 243
  • 3
  • 10

1 Answers1

0

The simplest way is to insert an id on the script tag which you can then locate in the DOM.

<script id="myscript">
    var s = document.getElementById("myscript");
</script>

You can also insert your own DOM element inline with the script and then find that:

<script>
    document.write('<div id="myDiv"></div>');
    var d = document.getElementById("myDiv");
</script>

If the script is an external script and you don't control the tag that loads it (so you can't put an id on it), but you do control the URL that it is loaded from, then you can search all script tags for the script tag that has a .src property that matches the origin of the script.

<script src="http://whatever.com/myscript.js"></script>

Then, inside of myscript.js, you can have this code:

function findScriptTag(href) {
    var tags = document.getElementsByTagName("script");
    for (var i = 0; i < tags.length; i++) {
        if (tags[i].src === href) {
            return tags[i];
        }
    }
    return null;
 }

 var s = findScriptTag("http://whatever.com/myscript.js");
jfriend00
  • 683,504
  • 96
  • 985
  • 979