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.
- First reference the parent node to add the new child element to
- Create a new <a> element using document.createElement(‘a’);
- Set the “href” attribute value for the <a>
- Create a new text node using document.createTextNode();
- Append the text node to the <a> element
- 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:
Web Browser Output after button is clicked: