Quick Answer: Dynamically Adding a Hyperlink to the DOM

December 29, 2007

Javascript is capable of appending child elements to the DOM of a web page dynamically. This quick answer demonstrates one way to append a <a> element to a <div>.

How to append a hyperlink to the DOM is relatively straight forward.

  1. First reference the parent node to add the new child element to
  2. Create a new <a> element using document.createElement(‘a’);
  3. Set the “href” attribute value for the <a>
  4. Create a new text node using document.createTextNode();
  5. Append the text node to the <a> element
  6. Finally, append the new <a> element to the parent node

<html>
  <head>
    <script language="Javascript">
      function appendLink()
      {
        //Get the element that we want to append to
         var divEl = document.getElementById('link_div');
        //Create the new <a>
        var aElem = document.createElement('a');
        aElem.href="http://www.google.com";
        //Create a text node to hold the text of the <a>
        var aElemTN = document.createTextNode('link to Google.com');
        //Append the <a> text node to the <a> element
        aElem.appendChild(aElemTN);
        //Append the new link to the existing <div>
        divEl.appendChild(aElem);
      }
    </script>
  </head>
  <body>
    <input type="button" value="Add Link" onClick="appendLink();">
    <div id="link_div"></div>
  </body>
</html>

Web Browser Output of code before button is clicked:

Dynamically Adding a Hyperlink 001

Web Browser Output after button is clicked:
Dynamically Adding a Hyperlink 002