DOM: Get Current Script Tag

By Xah Lee. Date: . Last updated: .

This is the best way to get the current script tag

document .currentScript → return the current script element.

// best way to get the current script tag
const scriptTag = document .currentScript;

It's supported by all major browsers since 2015. (it's not supported by Internet Explorer version 11)

Other ways are get by id, which is very good, but requires you add an id attribute.

[see DOM: Get Elements by ID, Tag, Name, Class, CSS Selector]

Alternatives for Older Browser

you can match your JavaScript file name.

// get the script element, by matching the script name
const scriptTag = document .querySelector('script[src$="my_script_name.js"]');
// alternative, get the script element, by matching the script name
const scriptTag = Array.prototype.filter.call(
    document .getElementsByTagName("script") ,
    function (e) {return e.src.indexOf("my_script_name.js") >= 0;}
)[0];
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog