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.

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];
Like it? Help me by telling your friends. Or, 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. CSS
  3. JavaScript
  4. JS Obj Ref
  5. DOM
  6. SVG
  7. Blog