DOM: Get Current Script Element

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];
βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


DOM

Overview

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc

jQuery

node.js