169

I have a string for a title and a string for a link. I'm not sure how to put the two together to create a link on a page using JavaScript. Any help is appreciated.

The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs. I would like to link the titles to the URL to make the page useful.

I am using jQuery but am completely new to it and wasn't aware it could help in this situation.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Xavier
  • 8,828
  • 13
  • 64
  • 98
  • Are you loading the RSS feed with jQuery or something (Mootools, Dojo, Atlas, etc...)? If you're trying to dynamically create anchor tags based on a third-party RSS list acquired on page load, I would suggest using the jQuery library or other to add the element. The details in this case are important to know what needs to be done. However, DOM methods are a useful illustration. – Jared Farrish Jan 23 '11 at 07:57
  • try this [link](http://stackoverflow.com/a/2433199/5996253) I think it can be beneficial – Yitzhak Weinberg Mar 29 '16 at 13:57

8 Answers8

282
<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>
Harry Moreno
  • 10,231
  • 7
  • 64
  • 116
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • 1
    This is a very generic example of using DOM methods to add an anchor tag to a page. For instance, the appendChild method could be a list element, TD, or other element within the page. See: http://www.quirksmode.org/ – Jared Farrish Jan 23 '11 at 07:51
  • 14
    @Nadu - Please stop editing my answer. If you want a specific thing to be said, add one of your own; if it's not "different" enough to warrant it, it's not different enough to warrant an edit. – Jared Farrish Jan 30 '17 at 17:36
  • https://plnkr.co/edit/mV7nOBIHa6hMNaVIPG75?p=preview I have been created a plunker example. – Harold Castillo Sep 15 '17 at 17:30
69

With JavaScript

  1. 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 element
    document.getElementsByTagName('body')[0].appendChild(a);
    
  2. document.getElementsByTagName('body')[0].innerHTML += '<a href="'+desiredLink+'">'+desiredText+'</a>';
    

    or, as suggested by @travis :

    document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
    
  3. <script type="text/javascript">
    //note that this case can be used only inside the "body" element
    document.write('<a href="'+desiredLink+'">'+desiredText+'</a>');
    </script>
    

With JQuery

  1. $('<a href="'+desiredLink+'">'+desiredText+'</a>').appendTo($('body'));
    
  2. $('body').append($('<a href="'+desiredLink+'">'+desiredText+'</a>'));
    
  3. 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.

Community
  • 1
  • 1
gion_13
  • 41,171
  • 10
  • 96
  • 108
  • 3
    I think that the only one that you left out is: `document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);` – travis Oct 03 '12 at 01:05
  • 1
    In order to avoid XSS, you should avoid string concatenation (`+`) and `.innerHTML` when building HTML. With jQuery, `.attr("href", desiredLink)` and `.text(desiredText)` are what you want here. – Wes Turner Dec 17 '14 at 01:51
20

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>
Naveed
  • 41,517
  • 32
  • 98
  • 131
16

There are a couple of ways:

If you want to use raw Javascript (without a helper like JQuery), then you could do something like:

var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";

// and append it to where you'd like it to go:
document.body.appendChild(element);

The other method is to write the link directly into the document:

document.write("<a href='" + link + "'>" + text + "</a>");
Roopinder
  • 309
  • 1
  • 3
  • I definitely like the first option better. +1 for that, but mixing JS and HTML mixes content and behavior, which should be separate. Overdone, that can lead to a maintenance nightmare. – jamesmortensen Jan 23 '11 at 07:56
  • I tend to prefer the first option as well, but perhaps using JQuery to achieve the same effect (for readability and ease of maintenance). – Roopinder Jan 23 '11 at 08:49
  • 1
    You should probably avoid using document.write http://stackoverflow.com/questions/4520440/javascript-document-write-overwriting-page – TryHarder Aug 08 '12 at 07:58
5

    <script>
      _$ = document.querySelector  .bind(document) ;

        var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
        var a   =  document.createElement( 'a' )
        a.text  = "Download example" 
        a.href  = "//bit\.do/DeezerDL"

        AppendLinkHere.appendChild( a )
        

     // a.title = 'Well well ... 
        a.setAttribute( 'title', 
                         'Well well that\'s a link'
                      );
    </script>
  1. The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear! Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. Leave the protocol open. Instead of http://example.com/path consider to just use //example.com/path. Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.

  3. OffTopic: That's not really relevant about creating links in JS but maybe good to know: Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.

Nadu
  • 2,401
  • 1
  • 25
  • 30
5

Dynamically create a hyperlink with raw JavaScript:

   var anchorElem = document.createElement('a');
   anchorElem.setAttribute("href", yourLink);
   anchorElem.innerHTML = yourLinkText;

   document.body.appendChild(anchorElem); // append your new link to the body
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
  • 1
    Use ` anchorElem.text = yourLinkText; ` instead of innerHTML that'll be more clear. And yes consider what'll happen if yourLinkText is maybe " < - that's cool !" – Nadu Feb 01 '17 at 17:23
0

A dirty but quick way to create elements:


const linkHTML = `<a
  class="my-link"
  style="position: absolute; right: 0"
  href="https://old.reddit.com"
  title="Go to old reddit"
>
  Old Reddit
</a>`;

  // create element
  const linkEl = strToElement(linkHTML);

  // add element to document.body
  document.body.appendChild(linkEl);

// utility function that converts a string to HTML element
function strToElement(s) {
  let e = document.createElement('div');
  const r = document.createRange();
  r.selectNodeContents(e);
  const f = r.createContextualFragment(s);
  e.appendChild(f);

  e = e.firstElementChild;
  return e;
}

GorvGoyl
  • 42,508
  • 29
  • 229
  • 225
-7

You paste this inside :

<A HREF = "index.html">Click here</A>