Javascript DOM HTML Element setAttribute() Method add href to <a>

Introduction

Add a href attribute with a value of "www.java2s.com" to an <a> element:

Click the button to set the href attribute with a value of "www.java2s.com" of the a element above.

View in separate window

<!DOCTYPE html>
<html>
<body>
<a id="myAnchor">A Link: Go to java2s.com</a>
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {// w w  w  . jav a  2s  . co  m
  document.getElementById("myAnchor").setAttribute("href", "https://www.java2s.com");
}
</script>

</body>
</html>



PreviousNext

Related