Javascript DOM HTML document createAttribute() Method create anchor element and set href

Introduction

Create a href attribute, with the value "www.java2s.com", and insert it to an <a> element:

Click the button to create a "class" attribute with the value "www.java2s.com" and insert it to the a element.

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() {/*from   www.ja  va  2  s  .c  o m*/
  var anchor = document.getElementById("myAnchor");
  var att = document.createAttribute("href");
  att.value = "https://www.java2s.com";
  anchor.setAttributeNode(att);
}
</script>

</body>
</html>



PreviousNext

Related