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="https://mzl.la/2qwFnRM">String.prototype.link 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.

Syntax

'click me!'.link('http://www.google.com')

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

Example

var text = 'String.prototype.link on MDN';
var url = 'https://mzl.la/2qwFnRM';

'Want to read more? Check out ' + text.link(url);

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:

WordPress.com Logo

You are commenting using your WordPress.com 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