This is untested, but you could maybe look for something better about the script that identifies the tag manager, such as part of the URL. Let's get the full source URL for the script that loads:
var tagManagerUrl = $('script[src*="googletagmanager"]').attr('src');
Now you have the URL whose query string contains the ID, but we need a way to parse the query string value from it. Let's take a look at the code from this answer, which gets a query string value by name from the current location.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
It's close, but we have to modify it to allow us to pass in our own query string:
function getParameterByName(qs, name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(qs);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
Now we can use it to find the id
value, which should be your container ID:
var tagManagerContainerId = getParameterByName(tagManagerUrl.split('?')[1], 'id');
// do something with it
You will need to run this after the tag manager itself loads.