The More You Know – Creating anchor links with JavaScript

If you create anchor elements via JavaScript regularly, then I hope you’ll find this first entry in The More You Know to be handy.

Your current process probably consists of a function that you pass what you’d like the user to see as well as the link they will navigated to and ultimately returning this

<a href=""> on MDN</a>

Well delete that function and feel good about it! It turns out the String prototype in JavaScript includes a function called link that does exactly that. MDN describes the function as a method that creates a string representing the code for an HTML element to be used as a hypertext link to another URL.


'click me!'.link('')

There’s a single string parameter that specifies that href attribute of the anchor element. It returns a string containing an anchor element.


var text = ' on MDN';
var url = '';

'Want to read more? Check out ' +;

Find this helpful? Why not share with your network

Take care

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s