Javascript Reference - HTML DOM Anchor Object








The Anchor object represents an HTML <a> element.

Standard Properties and Events

The Anchor object supports the standard properties and events.

Example

We can access an <a> element by using getElementById().


<!DOCTYPE html>
<html>
<body>
<a id="myAnchor" href="http://www.example.com">Tutorials</a>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!-- w w  w . ja  v a 2  s  . co  m-->
    var x = document.getElementById("myAnchor").href;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

We can create an <a> element by using the document.createElement() method.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!-- w ww  .  java 2s.  c  o  m-->
    var x = document.createElement("A");
    var t = document.createTextNode("Tutorials");
    x.setAttribute("href", "http://www.example.com");
    x.appendChild(t);
    document.body.appendChild(x);
}
</script>
</body>
</html>

The code above is rendered as follows:





Anchor Object Properties

Property Description
charset Not supported in HTML5.
Sets or gets the charset attribute of a link
download Sets or gets the download attribute of a link
hash Sets or gets the anchor part of the href attribute value
host Sets or gets the hostname and port of the href attribute value
hostname Sets or gets the hostname part of the href attribute value
href Sets or gets the href attribute of a link
hreflang Sets or gets the hreflang attribute of a link
origin Returns the protocol, hostname and port of the href attribute value
id Sets or gets the id attribute of a link
name Not supported in HTML5. Use id instead.
Sets or gets the name attribute of a link
password Sets or gets the password part of the href attribute value
pathname Sets or gets the pathname of the href attribute value
port Sets or gets the port of the href attribute value
protocol Sets or gets the protocol of the href attribute value
rel Sets or gets the rel attribute of a link
rev Not supported in HTML5.
Sets or gets the rev attribute of a link
search Sets or gets the query string of the href attribute value
target Sets or gets the target attribute of a link
text Sets or gets the link text
type Sets or gets the type attribute of a link
username Sets or gets the username in the href attribute value