var link = document.createElement("A"); link.href = "http://www.google.com"; var atext = document.createTextNode("Google"); link.appendChild(atext); oElement.appendChild(link);First, you create an HTMLAnchorElement using a DOM method createElement(tagName).
var link = document.createElement("A");Then, you set the href property of the HTMLAnchorElement:
link.href = "http://www.google.com";Next, you create a text node that will hold the clickable text:
var atext = document.createTextNode("Google");Then, append the text node to the HTMLAnchorElement:
link.appendChild(atext);Now, you can append the link element to another element on the page:
oElement.appendChild(link);oElement holds a reference to an HTML element on the page that will be a parent of the newly created hyperlink.
Here is the same code presented as a function that accepts 3 parameters: parent element, url and link text:
function createLink(parent, url, linkText){ var link = document.createElement("A"); link.href = url; var atext = document.createTextNode(linkText); link.appendChild(atext); parent.appendChild(link); }
No comments:
Post a Comment