Best way to create a link using JQuery?
Asked Answered
S

6

28

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?

Slabber answered 23/11, 2010 at 22:34 Comment(0)
S
18

As Steven Xu correctly mentioned, inserting HTML strings is faster than manipulating the DOM, which is why I'd recommend creating elements with string manipulation instead of jQuery.

You need only change this:

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

to this:

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

(close <a> tag with </a> at the end of the string).

The string manipulation is much faster than the DOM Manipulation (see this for example). Moreover the difference will be much more if you try to insert a DOM fragment in the middle of a large HTML code. The usage of DOM DocumentFragments can a little improve the performance, but the usage of the string concatenation is the fastest way.

All other answers wrote his answer without the knowledge about the context (jqGrid custom formatter) where you use it. I try to explain why it is important in your case.

Because of performance advantages, jqGrid builds HTML code fragments for the grid first as the array of strings, then build one string from the string array with respect of .join('') and insert the result in the table body at the end of all only. (I suppose that you use gridview:true jqGrid option which is almost always recommended). The jqGrid custom formatter is a callback function used by jqGrid during the building of the grid (table) body. The custom formatter must return the HTML code fragment as the string as the result. The string will be concatenated with other strings which build the body of the grid (table).

So if you will change your current code from pure string manipulation to the jQuery DOM manipulation and converting the results to the string (which needed be returned as the result of the custom formatting) then your code will work slowly and you will have no other advantages*.

The only real disadvantage of the usage of the string manipulations is the problem of the verification of the code which you build. For example, the usage of code without the close tags </a> is a potential problem which you can have. In the most cases the problem will be solved during the inserting of the DOM fragment, but sometimes you can receive real problems. So you should just test the code which you inserted very carefully.

One more remark: If you want to follow unobtrusive JavaScript style you can use "#" as the value for the href attribute and bind the corresponding click event inside of gridComplete or loadComplete event handler. If you will have problems with the implementation of this you can open a new question and I will try to write the corresponding code example for you.

Note: I think the best implementation way will be the usage of onCellSelect or beforeSelectRow instead of binding click event to every <a> element in the column. I recommend to read the following answers for details: this one, another one and one more old answer.

Shawm answered 24/11, 2010 at 11:8 Comment(2)
"the inserting of HTML string is faster as the DOM" - Sure, it's also the best way to ensure you have tons of XSS problems.Encomiastic
@oreoshake: Sorry, but I'm not sure that I understand you correctly. The question which I answered was about the usage of jqGrid custom formatters. It's callbacks used by jqGrid to construct the HTML content of cells in specific column. So the custom formatters have to return string because it's requirement of jqGrid interface. The requirement exists because jqGrid build all rows of the grid as one string* and insert it as one DOM operation. It improves performance. The answer of "Gaby aka G. Petrioli" has no relation with the question because it can't be used with jqGrid.Shawm
C
114

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)

Coelostat answered 23/11, 2010 at 22:58 Comment(0)
S
18

As Steven Xu correctly mentioned, inserting HTML strings is faster than manipulating the DOM, which is why I'd recommend creating elements with string manipulation instead of jQuery.

You need only change this:

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

to this:

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

(close <a> tag with </a> at the end of the string).

The string manipulation is much faster than the DOM Manipulation (see this for example). Moreover the difference will be much more if you try to insert a DOM fragment in the middle of a large HTML code. The usage of DOM DocumentFragments can a little improve the performance, but the usage of the string concatenation is the fastest way.

All other answers wrote his answer without the knowledge about the context (jqGrid custom formatter) where you use it. I try to explain why it is important in your case.

Because of performance advantages, jqGrid builds HTML code fragments for the grid first as the array of strings, then build one string from the string array with respect of .join('') and insert the result in the table body at the end of all only. (I suppose that you use gridview:true jqGrid option which is almost always recommended). The jqGrid custom formatter is a callback function used by jqGrid during the building of the grid (table) body. The custom formatter must return the HTML code fragment as the string as the result. The string will be concatenated with other strings which build the body of the grid (table).

So if you will change your current code from pure string manipulation to the jQuery DOM manipulation and converting the results to the string (which needed be returned as the result of the custom formatting) then your code will work slowly and you will have no other advantages*.

The only real disadvantage of the usage of the string manipulations is the problem of the verification of the code which you build. For example, the usage of code without the close tags </a> is a potential problem which you can have. In the most cases the problem will be solved during the inserting of the DOM fragment, but sometimes you can receive real problems. So you should just test the code which you inserted very carefully.

One more remark: If you want to follow unobtrusive JavaScript style you can use "#" as the value for the href attribute and bind the corresponding click event inside of gridComplete or loadComplete event handler. If you will have problems with the implementation of this you can open a new question and I will try to write the corresponding code example for you.

Note: I think the best implementation way will be the usage of onCellSelect or beforeSelectRow instead of binding click event to every <a> element in the column. I recommend to read the following answers for details: this one, another one and one more old answer.

Shawm answered 24/11, 2010 at 11:8 Comment(2)
"the inserting of HTML string is faster as the DOM" - Sure, it's also the best way to ensure you have tons of XSS problems.Encomiastic
@oreoshake: Sorry, but I'm not sure that I understand you correctly. The question which I answered was about the usage of jqGrid custom formatters. It's callbacks used by jqGrid to construct the HTML content of cells in specific column. So the custom formatters have to return string because it's requirement of jqGrid interface. The requirement exists because jqGrid build all rows of the grid as one string* and insert it as one DOM operation. It improves performance. The answer of "Gaby aka G. Petrioli" has no relation with the question because it can't be used with jqGrid.Shawm
P
12
jQuery('<a>').attr('href', 'url').text('blah')

Will make a jquery object and you can then just add it to the dom with .append.

Publicspirited answered 23/11, 2010 at 22:37 Comment(2)
Is there a way to just return the raw HTML? Something like jQuery('<a>').attr('href', 'url').text('blah').html()?Slabber
only way I was able to do this was to append this to another div and get the html of that. like: jQuery('<div>').append(jQuery('<a>').attr('href', 'url').text('blah')).html() .html will only get what's inside the current element, so i had to wrap that inside something else. But TBH, what you have in your question is fine. I used jQGrid before and that's how I did it.Publicspirited
B
9

My preferred way is this:

$("<a>", {
  title: "Blah",
  href: "javascript:BlahFunc('" + options.rowId + "')"
  }).append( "This is blah" );

There's good information in this article:
http://marcgrabanski.com/articles/building-html-in-jquery-and-javascript

Bernete answered 23/11, 2010 at 22:39 Comment(1)
good call, i was going off the article but i always forget that you do actually need the brackets.Bernete
E
1

In general, inserting an HTML string is faster and multiple DOM injections and DOM manipulations, which is what this jQuery DOM manipulation amounts to. If you wanted to insert 500 of these, the best option, performance-wise, would be to prepare the HTML string and then append the HTML.

But for your simple purposes, you current option will suit you just fine. For cleverer, you might use jQuery's DOM manipulation library on your new elements. The below example should be self-explanatory, but if I haven't been clear in a particular are, leave a comment, and I'll help you out.

var toBeAdded = [
  { title: "one", row: 1, content: "ONE" },
  { title: "two", row: 2, content: "TWO" },
  { title: "three", row: 3, content: "THREE" }
];

var s = toBeAdded.length;
for(i=0;i<s;i++) {
  var a = $('<a>');
  a.attr('title', toBeAdded[i].title);
  a.attr('rel', toBeAdded[i].row);
  a.text(toBeAdded[i].content);
  a.addClass('blah_class');
  a.appendTo($('body'));
}

And then in your universal script:

$('a.blah_class').live('click', function(){
  var rel = $(this).attr('rel');
  BlahFunc(rel);
});
Endermic answered 23/11, 2010 at 22:43 Comment(0)
I
0

This is what helped me, get link from button for new link

var $jsClonedButtonLinkContainer = $('.js-cloned-button-link-container');
$jsClonedButtonLinkContainer.each(function() {
    $('<a>', {
      href: $(this).find('a.nectar-button').attr('href'),
      'class': 'flip-box__cloned-button-link'
    }).prependTo($(this).find('.flip-box-back'));
  });
Interdigitate answered 1/12, 2020 at 0:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.