Javascript Reference - HTML DOM Anchor hash Property








The hash property sets or gets the anchor part of the href attribute value.

The anchor is the part of the URL after the hash sign (#).

Browser Support

hash Yes Yes Yes Yes Yes

Syntax

Return the hash property:

var value = anchorObject.hash;

Set the hash property:

anchorObject.hash = anchorname;




Property Values

Value Description
anchorname Set the URL anchor

Return Value

A String representing the URL anchor including the hash sign (#).

Example

The following code shows how to get the anchor part of a link.


<!DOCTYPE html>
<html>
<body>
<!--from  w  w  w.j ava2  s.c o  m-->
<p><a id="myAnchor" href="http://www.example.com:80/test.htm#part2">Example link</a></p>
<p id="demo"></p>

<button onclick="myFunction()">test</button>

<script>
function myFunction() {
    var x = document.getElementById("myAnchor").hash;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to set the anchor part of a link.


<!DOCTYPE html>
<html>
<body>
<!--from w  w  w . j  a  v  a 2 s  . co m-->
<p><a id="myAnchor" target="_blank" href="http://www.example.com/test.htm#part2">Example link</a></p>
<button onclick="myFunction()">test</button>

<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("myAnchor").hash = "newhashvalue";
    document.getElementById("demo").innerHTML = "changed";
}
</script>

</body>
</html>

The code above is rendered as follows: