How do I create a link using javascript?
<html> <head></head> <body> <script> var a = document.createElement('a'); var linkText = document.createTextNode("my title text"); a.appendChild(linkText); a.title = "my title text"; a.href = "http://example.com"; document.body.appendChild(a); </script> </body></html>
With JavaScript
var a = document.createElement('a');a.setAttribute('href',desiredLink);a.innerHTML = desiredText;// apend the anchor to the body// of course you can append it almost to any other dom elementdocument.getElementsByTagName('body')[0].appendChild(a);
document.getElementsByTagName('body')[0].innerHTML += '<a href="'+desiredLink+'">'+desiredText+'</a>';
or, as suggested by @travis :
document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
<script type="text/javascript">//note that this case can be used only inside the "body" elementdocument.write('<a href="'+desiredLink+'">'+desiredText+'</a>');</script>
With JQuery
$('<a href="'+desiredLink+'">'+desiredText+'</a>').appendTo($('body'));
$('body').append($('<a href="'+desiredLink+'">'+desiredText+'</a>'));
var a = $('<a />');a.attr('href',desiredLink);a.text(desiredText);$('body').append(a);
In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink
is a variable that holds the address that your anchor element points to, and desiredText
is a variable that holds the text that will be displayed in the anchor element.
Create links using JavaScript:
<script language="javascript"><!--document.write("<a href=\"www.example.com\">");document.write("Your Title");document.write("</a>");//--></script>
OR
<script type="text/javascript">document.write('Your Title'.link('http://www.example.com'));</script>
OR
<script type="text/javascript">newlink = document.createElement('a');newlink.innerHTML = 'Google';newlink.setAttribute('title', 'Google');newlink.setAttribute('href', 'http://google.com');document.body.appendChild(newlink);</script>