177

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.

2
  • 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. Commented Jan 23, 2011 at 7:57
  • try this link I think it can be beneficial Commented Mar 29, 2016 at 13:57

8 Answers 8

299
<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>
Sign up to request clarification or add additional context in comments.

3 Comments

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: quirksmode.org
@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.
plnkr.co/edit/mV7nOBIHa6hMNaVIPG75?p=preview I have been created a plunker example.
73

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.

2 Comments

I think that the only one that you left out is: document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
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.
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>

Comments

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>");

3 Comments

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.
I tend to prefer the first option as well, but perhaps using JQuery to achieve the same effect (for readability and ease of maintenance).
You should probably avoid using document.write stackoverflow.com/questions/4520440/…
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

1 Comment

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 !"
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.

Comments

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;
}

Comments

-8

You paste this inside :

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

1 Comment

The OP is explicitly asking for creating a link with JavaScript (not HTML) !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.