Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- How do I code hyperlinks in Javascript?


rewboss - 9:55 am on Jul 8, 2002 (gmt 0)


JavaScript also has a function called String.link() which adds <a> tags:

document.write('My site'.link('http://www.mysite.com'));

That seems like a long way around the problem, but if you have stored the links and texts in variables, it makes it easier to automate the process. So, instead of, for example:

document.write('<a href="'+hyperLink[i].url+'">'+hyperLink[i].text+'</a>');

you can write:

document.write(hyperLink[i].text.link(hyperLink[i].url));

You could probably make the code even easier with the with statement, though this is discouraged:

with(hyperLink[i]) document.write(text.link(url));

The obvious drawback is that you can't add any extra attributes, such as title or class.

(Yeah, I'm always on the lookout for ways to cut down on the amount of code I write.)


Thread source:: http://www.webmasterworld.com/javascript/150.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com