ekyo-g
Last Updated: February 25, 2016
·
1.867K
· idered
190043 533696520020804 1840519452 n

[JS] Not well known link() method

Probably every jQuery developer know how to create link with it:

$('<a href="http://google.com"/>').text('Google');

or:

$('<a href="http://google.com">Google</a>');

But there's also a little know link() method:

'Google'.link('http://google.com');
Say Thanks
Respond

5 Responses
Add your response

3418
D42a7264714dee5006b9c99d2567a320

Interesting find! Is there a spec for the function somewhere? I wonder what's the browser support...

over 1 year ago ·
4214
42595607ede5ee9c75f4da244128a082

Wow!

W3Schools says it's supported in "All Major Browsers". A quick test in Firefox, IE7, and Chrome shows it works in all of those.

I never expected a method like that on the String object. It's very Pythonic...

over 1 year ago ·
4215
Mich400x400

I think the jQuery reference to create links here is fairly irrelevant; jQuery is a popular library, while the actual subject of the post is about a (non-standard) feature.

There's a bunch more HTML-creation string prototype functions in the String prototype, which you can find on this MDN page: String.prototype

over 1 year ago ·
4237
76e58b41e1f6bfaa974ef403dbefc9f9

There are many other HTML wrapper methods in JS besides just link() too.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#HTML_wrapper_methods

over 1 year ago ·
5904

@michd : he's referring something that is done widely by javascript developers and shows what is probably the most common way to achieve it, then shows a simpler way. That's totally relevant to me.

On a side note, those are not totally identical :

$('<a href="/foo">foo</a>')
'foo'.link('/foo')

If you want to product the same result, you have to do this :

$( 'foo'.link('/foo') )

And you can"t specify other attributes, like data-* or title, so it won't replace your link creation usual ways everywhere.

Still a nice tip, though, thanks for sharing !

over 1 year ago ·