HTML DOM Anchor text Property



The HTML DOM text property associated with the anchor tag (<a>) specifies the text part of an anchor tag.

For example − <a href=”www.google.com”>Google</a>. Here the text part is Google. Using the text property we can get or change the value of anchor text.

Syntax

Following is the syntax for −

Returning the text property −

anchorObject.text

Setting the text property −

anchorObject.text = sometext

Example

Let us see an example for anchor text property −

<!DOCTYPE html>
<html>
<body>
<p><a id="Anchor" href="http://www.examplesite.com">Example site</a></p>
<p>Click the button below to change the text content of the link above.</p>
<button onclick="ChangeText()">Click it</button>
<button onclick="GetText()">Get Text</button>
<p id="Sample"></p>
<script>
   function ChangeText() {
      document.getElementById("Anchor").text = "Click here to open examplesite";
   }
   function GetText(){
      var x=document.getElementById("Anchor").innerHTML;
      document.getElementById("Sample").innerHTML=x;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking “Click it” −

On clicking “Get Text” −

In the above example −

We have taken an anchor tag with “example site” as link text

<p><a id="Anchor" href="http://www.examplesite.com">Example site</a></p>

We have then created two buttons “Click it” and “Get Text” to execute functions ChangeText() and GetText() respectively.

<button onclick="ChangeText()">Click it</button>
<button onclick="GetText()">Get Text</button>

The ChangeText() function will change the anchor text from “Example site” to “Click here to open examplesite” while the GetText() function get the anchor text from the link with id specified as anchor and display it in the paragraph with id Sample associated with it.

raja
Published on 06-Aug-2019 15:54:36
Advertisements