Javascript Reference - HTML DOM Base href Property








The href attribute from base element specifies a base URL for all relative URLs on a page.

The href property sets or gets the value of the href attribute in a base element.

Browser Support

href Yes Yes Yes Yes Yes

Syntax

Return the href property:

var aValue = baseObject.href;

Set the href property:

baseObject.href = URL




Return Value

A string value representing the base URL.

Example

The following code shows how to change the value of the base URL.


<!DOCTYPE html>
<html>
<head>
<base id="myBase" href="http://java2s.com/new/">
</head><!--from   ww  w  . jav a 2s .co  m-->
<body>
<a href="wrongFile.html">Default</a>
<p id="demo"></p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("myBase").href = "http://java2s.com/html/";
    document.getElementById("demo").innerHTML = "changed";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to get the base URL.


<!DOCTYPE html>
<html>
<head>
<base id="myBase" href="http://www.java2s.com/new/">
</head><!--from  www.  j a v  a 2s .c  o m-->
<body>
<p id="demo"></p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    var x = document.getElementById("myBase").href;
    document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>

The code above is rendered as follows: