In joomla php there I can use $this->baseurl
to get the base path, but I wanted to get the base path in jquery.
The base path may be any of the follo
I am surprised that non of the answers consider the base url if it was set in
tag. All current answers try to get the host name or server name or first part of address. This is the complete logic which also considers the
tag (which may refer to another domain or protocol):
function getBaseURL(){
var elem=document.getElementsByTagName("base")[0];
if (typeof(elem) != 'undefined' && elem != null){
return elem.href;
}
return window.location.origin;
}
Jquery format:
function getBaseURL(){
if ($("base").length){
return $("base").attr("href");
}
return window.location.origin;
}
Without getting involved with the logic above, the shorthand solution which considers both
tag and window.location.origin
:
Js:
var a=document.createElement("a");
a.href=".";
var baseURL= a.href;
Jquery:
var baseURL= $('')[0].href
Final note: for a local file in your computer (not on a host) the window.location.origin
only returns the file://
but the sorthand solution above returns the complete correct path.