HTML DOM Anchor username Property


The HTML DOM anchor username property associated with anchor tag is used to set or return the value of the username part of the href attribute. The username is entered by the user and is often used in username-password pair. The username value is specified after the protocol and just before the password part of the link.

Syntax

Following is the syntax for −

Returning the username property −

anchorObject.username

Setting the username property −

anchorObject.username = UsernameValue

Example

Let us see an example of anchor username property −

 Live Demo

<!DOCTYPE html>
<html>
<body>
<p><a id="Anchor"href="https://john:john123@www.examplesite.com">ExampleSite</a></p>
<p>Click the button to change username</p>
<button onclick="changeUser()">Set User</button>
<button onclick="GetUser()">Get User</button>
<p id="Sample"></p>
<script>
   function changeUser() {
      document.getElementById("Anchor").username = "Rohan";
   }
   function GetUser() {
      var x=document.getElementById("Anchor").username;
      document.getElementById("Sample").innerHTML = x;
   }
</script>
</body>
</html>

Output

It will produce the following output −

On clicking “Set User” −

On clicking “Get User” −

In the above example −

We have taken a link with username as john and password john123.

<p><a id="Anchor" href="https://john:john123@www.examplesite.com">ExampleSite</a></p>

We have then two buttons “Set User” and “Get User” to execute functions changeUser() and GetUser() respectively.

<button onclick="changeUser()">Set User</button>
<button onclick="GetUser()">Get User</button>

The changeUser() function changes the username specified in the link to the username specified by us; ”Rohan” in our case. The GetUser() function gets the username from the link with id Anchor associated with it and returns “Rohan” only if changeUser() is called before GetUser().Otherwise it will be “john”.

function changeUser() {
   document.getElementById("Anchor").username = "Rohan";
}
function GetUser() {
   var x=document.getElementById("Anchor").username;
   document.getElementById("Sample").innerHTML = x;
}

Updated on: 20-Feb-2021

67 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements