Javascript DOM HTML Element hasAttribute() Method check anchor target attribute

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() {/*  ww w .j a  va  2  s  .  co m*/
  var x = document.getElementById("myAnchor");

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

</body>
</html>



PreviousNext

Related