Best way to create a link using JQuery?

Marcus Leon picture Marcus Leon · Nov 23, 2010 · Viewed 84k times · Source

We use jqGrid custom formatters to output links in our JQuery grids. We just construct the links using String manipulation a la:

var s = "<a title=\"Blah\" href=\"javascript:BlahFunc('" + options.rowId + "')\">This is blah<a>";

Is there a more "clever" way to create links (and other form elements) using JQuery?

Answer

Gabriele Petrioli picture Gabriele Petrioli · Nov 23, 2010

I find the best to be

$('<a>',{
    text: 'This is blah',
    title: 'Blah',
    href: '#',
    click: function(){ BlahFunc( options.rowId );return false;}
}).appendTo('body');

Live example at http://www.jsfiddle.net/gaby/RhWgf/

I have replaced the inline javascript with an attached handler

Quote from the docs about jQuery()

jQuery( html, props )

html A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).
props An map of attributes, events, and methods to call on the newly-created element.


Update

If you want the actual text of the link you should wrap it in a div and return the .html() of that.

(alternatively: you can use access the .outerHTML property of the raw element)

Full example at http://www.jsfiddle.net/gaby/RhWgf/1/ (removed the click handler, as it would get lost in a string version, and replaced it with a live handler that targets the specific kind of links)