The HTML DOM Base object is associated with the HTML <base> element. The <base> element is used to specify the base url for all other URLs in the HTML document. There can at most one <base> element in an HTML document. The Base object is used to set or get the href attribute of the <base> element.
Properties
Following are the properties of Base object −
Property | Description |
---|---|
href | Sets or returns the value of the href attribute in a base element |
target | Sets or returns the value of the target attribute in a base element |
Syntax
Following is the syntax for −
Creating the base element −
document.createElement ("base")
Accessing the base element −
var a = document.getElementById("demoBase");
Example
Let us see an example of base object −
<!DOCTYPE html> <html> <body> <p>Create the element first and then access it</p> <p>Click the button below to create or access BASE element.</p> <button onclick="CreateBase()">CREATE</button> <button onclick="AcessBase()">ACCESS</button> <p id="SAMPLE"></p> <script> function CreateBase() { var x = document.createElement("BASE"); x.setAttribute("id","myBase"); x.setAttribute("href", "https://www.google.com"); document.head.appendChild(x); document.getElementById("SAMPLE").innerHTML = "BASE element with href https://www.google.com is created"; } function AcessBase() { var x = document.getElementById("myBase").href; document.getElementById("SAMPLE").innerHTML = x; } </script> </body> </html>
Output
This will produce the following output −
On clicking CREATE −
On clicking ACCESS −
In the above example −
We have created two buttons CREATE and ACCESS to execute CreateBase() and AccessBase() function respectively.
<button onclick="CreateBase()">CREATE</button> <button onclick="AcessBase()">ACCESS</button>
The CreateBase() function creates a base element and assigns it to variable x. Then using the setAttribute() method we set its id and href. The newly created base element is then appended to the document head using the appendChild() property. Finally the base creation message is displayed in the paragraph with id SAMPLE associated with it.
function CreateBase() { var x = document.createElement("BASE"); x.setAttribute("id","myBase"); x.setAttribute("href", "https://www.google.com"); document.head.appendChild(x); document.getElementById("SAMPLE").innerHTML = "BASE element with href https://www.google.com is created"; }
The AcessBase() function is created to access our newly created <base> element. It does so by getting the element by id and then getting its href value and assigning it to a variable named x. The information in x is then displayed into the paragraph with id SAMPLE .
function AcessBase() { var x = document.getElementById("myBase").href; document.getElementById("SAMPLE").innerHTML = x; }