Get BASE in HTML after it has been set, but not using page URL

No need for jquery, jqlite, or obsolete APIs. Use the newer querySelector API:

var base = document.querySelector('base');
var baseUrl = base && base.href || '';

Update 3

As @jorgecasar mentioned in his answer below, there is now a property, baseURI on every Node (which includes every Element).

Calling document.baseURI will get you the base path to the page, taking into account the <base> tag.

Note that it is a recent-ish property that is supported by all modern browsers, but if you are using older browsers you might either want to stick with the older answers or make sure you have a poly- or ponyfill for it (Babel's standard polyfill seems to include one, though I couldn't find specific documentation saying as much).

Also, note that document.baseURI will give you a fully-qualified absolute path, whereas getting the href attribute from <base> will give you the exact value you provided, so there may be a slight difference in the usage of the two.


Original

If you want to get the value of the base element, you can do something like:

var baseHref = document.getElementsByTagName('base')[0].href

Or to be a little safer:

var bases = document.getElementsByTagName('base');
var baseHref = null;

if (bases.length > 0) {
    baseHref = bases[0].href;
}

Update: a more concise way would be:

const baseHref = (document.getElementsByTagName('base')[0] || {}).href;

baseHref may be null if it doesn't have a <base>.


Update 2: Instead of using getElementsByTagName(), use querySelector():

var base = (document.querySelector('base') || {}).href;
console.log(base);
<base href="http://www.google.com"/>

Every Node has a readonly property baseURI that returns the absolute base URL or null if unable to obtain an absolute URI.

To obtain the base URL of a document you can use: document.baseURI.

If you only want the pathname or any other part of the URL you can create a URL object:

var baseLocation = new URL(document.baseURI);
var pathname = baseLocation.pathname;

One issue I ran into is that using element.href doesn't return exactly what is set. For example, if you have this:

<base href="/some/sub/directory/" />

Then element.href will give you:

document.getElementsByTagName('base')[0].href
# http://example.com/some/sub/directory/

I found that you can avoid this by using the jQuery attr function:

$("base").attr("href")
# /some/sub/directory/

If you want to avoid jQuery, you can also use the getAttribute function:

document.getElementsByTagName('base')[0].getAttribute("href")
# /some/sub/directory/