HTML DOM Anchor target Property

HTMLWeb DevelopmentFront End Technology

The HTML DOM target property associated with the anchor tag (<a>) specifies where the new web page will open after clicking the URL. It can have the following values −

  • _blank − This will open the linked document in a new window.
  • _parent − This will open the linked document in the parent frameset.
  • _top − This will open the linked document in the full body window.
  • _self − This will open the linked document in the same window. This is the default behavior
  • framename − This will open the linked document in the specified framename.

Syntax

Following is the syntax for −

Returning the target property −

anchorObject.target

Setting the target property −

anchorObject.target = "_blank|_self|_parent|_top|framename"

Example

Let us see an example of anchor target property −

Live Demo

<!DOCTYPE html>
<html>
<body>
<p><a id="Anchor" target="_self" href="https://www.examplesite.com">example site</a></p>
<p><a id="Anchor2" href="https://www.examplesite.com">example site</a></p>
<p>Click the button to see the value of the target attribute.</p>
<button onclick="getTarget1()">GetTarget</button>
<button onclick="setTarget2()">SetTarget</button>
<p id="Target1"></p>
<script>
   function getTarget1() {
      var x = document.getElementById("Anchor").target;
      document.getElementById("Target1").innerHTML = x;
   }
   function setTarget2(){
      document.getElementById("Anchor2").innerHTML="Target has been set";
      document.getElementById("Target1").target="newframe";
   }
</script>
</body>
</html>

Output

This will produce the following output −

After clicking on “GetTarget” button −

After clicking on “SetTarget” button −

In the above example −

We have taken one anchor tag with target attribute and with a value _self and another one with default _blank −

<p><a id="Anchor" target="_self" href="https://www.examplesite.com">example site</a></p>
<p><a id="Anchor2" href="https://www.examplesite.com">example site</a></p>

We have then created two buttons named GetTarget and SetTarget to execute the getTarget1() and setTarget2() functions respectively.

<button onclick="getTarget1()">GetTarget</button>
<button onclick="setTarget2()">SetTarget</button>

The getTarget1() will get the target value from the first link and display in the paragraph tag with id=”Target1”. The setTarget2() will set the target value of link2 from default _blank to custom frame “newframe”.

function getTarget1() {
   var x = document.getElementById("Anchor").target;
   document.getElementById("Target1").innerHTML = x;
}
function setTarget2(){
   document.getElementById("Target1").innerHTML="Target has been set";
   document.getElementById("Anchor2").target="_blank";
}
raja
Updated on 20-Feb-2021 06:34:16

Advertisements