The Preferred Way of Creating a New Element with Jquery

The preferred way of creating a new element with jQuery

The first option gives you more flexibilty:

var $div = $("<div>", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);

And of course .html('*') overrides the content while .append('*') doesn't, but I guess, this wasn't your question.

Another good practice is prefixing your jQuery variables with $:

Is there any specific reason behind using $ with variable in jQuery

Placing quotes around the "class" property name will make it more compatible with less flexible browsers.

Which is the correct or better way to create a new element with jQuery?

If you go solely by metrics that can be easily measured: The first is better because it is 2 bytes shorter.

Once you start accounting for readability and other less tangible considerations, it becomes largely a matter of opinion.

So, at the end it's wrong to use one of the first two options for a div?

No, that section only applies "If the HTML is more complex than a single tag without attributes"

What is the most efficient way to create HTML elements using jQuery?

I use $(document.createElement('div')); Benchmarking shows this technique is the fastest. I speculate this is because jQuery doesn't have to identify it as an element and create the element itself.

You should really run benchmarks with different Javascript engines and weigh your audience with the results. Make a decision from there.

Creating a div element in jQuery

You can use append (to add at last position of parent) or prepend (to add at fist position of parent):

$('#parent').append('<div>hello</div>');    
// or
$('<div>hello</div>').appendTo('#parent');

Alternatively, you can use the .html() or .add() as mentioned in a different answer.

Clearest way to build html elements in jQuery

Templates are great and if you have access to them in your project, I suggest you use them. If you're using Underscore or Lodash it's built in. In some cases however, you will need to build HTML in your code whether it's refactoring or testing. I've found that the below format is the clearest to read when that is the requirement.

Note: The HTML spec allows single OR double quotes for attributes in your markup so don't bother with all the crazy escaping.

this.$fixture = $([
"<div>",
" <div class='js-alert-box'></div>",
" <form id='my-form-to-validate'>",
" <input id='login-username' name='login-username'>",
" </form>",
"</div>"
].join("\n"));

which way of creating and appending an element is faster in jQuery?

The first method ought to be little bit faster, because it deals less with the DOM.

Here is a small test using performance.now() to measure execution time:

$(function() {

var s1 = performance.now();
$('#page123').append("<div id='foo' class='checkbox' data-quesid='foofaa'><label class='control-label'>Question<span class='quesNo'>2</span>: <span class='q'>2</span></label></div>")
var e1 = performance.now();
console.log('StringAppend: ' + (e1 - s1) + ' ms');

var s2 = performance.now();
var question = $('div.sampleQuestionLayOut').first().clone(true);
question.removeClass('sampleQuestionLayOut');
question.removeAttr('style');
question.attr('id', 'foo');
question.attr('data-quesid', 'foofaa');
question.html("<label class='control-label'>Question<span class='quesNo'>1</span>: <span class='q'>1</span></label>")
$('#page123').append(question);
var e2 = performance.now();
console.log('CloneAndAppend: ' + (e2 - s2) + ' ms');

})

https://jsfiddle.net/s1odw6pg/1/

I might add that generally speaking you should try to minimize the number of invocations of the append() method and thus the DOM-manipulations operations. If your elements need to appear one after another you can build a big HTML-string and append it all together. An interesting resource to see different approaches to this is the following: http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

jQuery creating elements - another .attr() vs .prop() question

I would go with attr() in that case. You're creating a new <a> element and setting its href HTML attribute, so it would make sense to emphasize that.

However, since the href attribute directly maps to the href DOM property, using prop() would have the exact same result.

Let's take another example, more relevant to the differences between attr() and prop(): suppose you want to set the class attribute of the <a> element instead of its href. The sample code in your question becomes:

  1. $('<a>').prop('className', '...');
  2. $('<a>').attr('class', '...');
  3. $('<a class="...">');

IMHO, (2) and (3) make one's intent clearer than (1). The fact that there cannot be a DOM property named class, because that token might be a reserved word in the host language, is at best an implementation detail. The class HTML attribute is usually what we're thinking about in that context.

Of course, there are situations where the opposite is true, e.g. when working with "boolean" HTML attributes like checked or disabled. In that case, it would be more robust to set the strongly-typed DOM property instead of creating the less well-defined HTML attribute.

Best way to create large static DOM elements in JavaScript?

Note: If you hate reading, just check summary down below for final answer

Maybe you don't really need to create those with help of jQuery.

If the structure of that html is complicated (hence using document.createElement approach would be an overkill) I would go with innerHTML attribute.

// somewhere in your code, preferably outside of global scope
var div = document.createElement('div')
div.id = 'mycustomdiv'
document.getElementsByTagName('body')[0].appendChild(div);
// assuming elements contains string of html with your elements
div.innerHTML = elements;

That way you avoid the (assuming again) unnecessary overhead of creating and wrapping the elements in jQuery object.


Update: test for yourself what's the fastest method http://jsperf.com/creating-complex-elements. This test confirms that when you're trying to squeeze every last bit of performance revert to vanilla javascript and classic DOM operations.


Update 2. To investigate why innerHTML method on Firefox 10 have such bad results in relation to passing full string to jQuery.append, I took a look at the jQuery source.

As it turns out (in jQuery 1.7.1), they're using yet another way of creating dom elements by utilizing document.createDocumentFragment (with some fallbacks of course for browsers that don't have proper support).

DocumentFragments are DOM Nodes. They are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children.

Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow.

Assuming createDocumentFragment is available it turns out to be the best approach in terms of overall cross-browser performance of script.

So, to sum up:

I stand corrected. If you're looking for best performance throughout different browsers when creating new DOM elements, focus on document fragments (use jQuery if you don't want to deal with various corner cases yourself).

For more reading concerning documentFragment check this post on John Resig blog http://ejohn.org/blog/dom-documentfragments/

What's the preferred way to create a jQuery object with attributes?

You can't use class; it's a reserved word.

Use className instead:

var $el = $('<div/>', {
className: 'class-1 class-2'
});

jQuery document.createElement equivalent?

Here's your example in the "one" line.

this.$OuterDiv = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;

Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about $("<div>") vs $("<div></div>") vs $(document.createElement('div')) as a way of creating new elements, and which is "best".

I put together a small benchmark, and here are roughly the results of repeating the above options 100,000 times:

jQuery 1.4, 1.5, 1.6

               Chrome 11  Firefox 4   IE9
<div> 440ms 640ms 460ms
<div></div> 420ms 650ms 480ms
createElement 100ms 180ms 300ms

jQuery 1.3

                Chrome 11
<div> 770ms
<div></div> 3800ms
createElement 100ms

jQuery 1.2

                Chrome 11
<div> 3500ms
<div></div> 3500ms
createElement 100ms

I think it's no big surprise, but document.createElement is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.


Update 2

Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!

http://jsben.ch/#/ARUtz



Related Topics



Leave a reply



Submit