HTML DOM Base href Property


The HTML DOM Base href property is associated with the <base> HTML tag. The <base> tag is used to specify the base URL for all relative URLs in the current HTML document. There can be a maximum of one <base> tag in a HTML document. The Base href Property returns the value of href attribute in the base element.

Syntax

Following is the syntax for −

Setting the href property −

baseObject.href = URL

Here, URL is the base URL.

Returning the href property −

baseObject.href

Example

Let us see an example for Base href Property −

<!DOCTYPE html>
<html>
<head>
<base id="myBase" href="https://www.bing.com">
</head>
<body>
<a href="/images">IMAGES</a>
<p>Click the below button to change href value of the above link</p>
<button onclick="SetHref()">SET IT</button>
<button onclick="GetHref()">GET IT</button>
<p id="Sample"></p>
<script>
   function SetHref() {
      document.getElementById("myBase").href = "https://duckduckgo.com";
      document.getElementById("Sample").innerHTML = "Base URL was changed from bing.com
      to duckduckgo.com";
   }
   function GetHref(){
      var x=document.getElementById("myBase").href;
   document.getElementById("Sample").innerHTML = x;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the SET IT button −

On clicking the GET IT button −

In the above example −

We have first created a  element with id “myBase” and attribute href with value equals https://www.bing.com

<base id="myBase" href="https://www.bing.com">

We have then created an anchor element with attribute href and value equals “/images”. Here the “/images” is a relative path as the base path is given in the base tag. Combining both the base and anchor element URL it will become https://www.bing.com/images.

<a href="/images">IMAGES</a>

We have then created two buttons SET IT and GET IT to call functions SetHref() and GetHref() respectively.

<button onclick="SetHref()">SET IT</button>
<button onclick="GetHref()">GET IT</button>

The SetHref() function gets the <base> element by using the “myBase” id. It then sets its URL by using the href property to https://www.duckduckgo.com. The change success message is displayed in the paragraph with id “Sample”.

function SetHref() {
   document.getElementById("myBase").href = "https://duckduckgo.com";
   document.getElementById("Sample").innerHTML = "Base URL was changed from bing.com to .comduckduckgo";
}

The GetHref() gets the <base> element by using the “myBase” id. It then gets its URL by using the href property and assigns it to variable x. The paragraph innerHTML is then changed using the innerHTML() property to x . This will display the href value of the <base> element.

function GetHref(){
   var x=document.getElementById("myBase").href;
   document.getElementById("Sample").innerHTML = x;
}

Updated on: 06-Aug-2019

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements