Quick Answer: Dynamically Adding a Hyperlink to the DOM

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

Advertisements

2 Responses to Quick Answer: Dynamically Adding a Hyperlink to the DOM

  1. Mikel says:

    Can this same method be used to add a javascript event to a link (i.e. can you add an “onclick” function by setting aElem.onclick=”clicked();”;)?

  2. Jennie says:

    Thank you sooooo much! My Javascript textbook only took 20 pages to talk about the DOM, and it didn’t cover much about creating links. This was extremely helpful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: