JavaScript: Get Current Script Tag

By Xah Lee. Date:

This is the best way to get the current script tag

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

you can read the spec at HTML Standard#dom-document-currentscript

though, doesn't seems to be supported by Internet Explorer, even version 11.

Other ways are get by id, which is very good, but requires the id tag.

〔➤see JavaScript: Get Elements by ID, Tag, Name, Class, CSS Selector

but, lastly, you can match your JavaScript file name.

// get the script element, by matching the script name
var scriptTag = document.querySelector('script[src$="my_script_name.js"]');
// alternative, get the script element, by matching the script name
var scriptTag = Array.prototype.filter.call(
    document.getElementsByTagName("script") ,
    function (e) {return e.src.indexOf("my_script_name.js") >= 0;}
)[0];
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.