Javascript DOM HTML Element setAttribute() Method set target of <a>

Introduction

Find out if an <a> element has a target attribute.

If so, change the value of the target attribute to "_self":

Click the button to find out if the a element has a "target" attribute.

If so, change the value of the target attribute to "_self_" instead of "_blank".

View in separate window

<!DOCTYPE html>
<html>
<body>

<a id="myAnchor" href="https://www.java2s.com" target="_blank">Go to java2s.com</a>.
<button id="myBtn" onclick="myFunction()">Test</button>
<script>
function myFunction() {//from w  ww .  j a v a  2s .  c o m
  var x = document.getElementById("myAnchor");

  if (x.hasAttribute("target")) {
    x.setAttribute("target", "_self");
  }
}
</script>

</body>
</html>



PreviousNext

Related