What Is the Most Efficient Way to Create HTML Elements Using Jquery

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.

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.

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"));

Fastest method to create HTML elements?

var txt1="<p>Text.</p>";               // Create element with HTML 
// actually: $('<p>Text.</p>');

In this case, jQuery will create a <div> element, then set its .innerHTML property to the HTML string you've passed. This is not particularly fast.

var txt2=$("<p></p>").text("Text.");   // Create with jQuery

This is much faster, because jQuery is optimized to map this straight to createElement() and you're using .text() so no additional parsing is required.

var txt3=document.createElement("p");  // Create with DOM
txt3.innerHTML="Text.";

This sidesteps some parts of the two approaches and should be faster, but isn't because you're using .innerHTML which has to get parsed first.

The fastest would be this:

var txt4 = document.createElement('p');
txt4.textContent = 'Text.';

Proof

Note that when I say fast, it's based on the results of this particular test case; normally you wouldn't get to a point where this would matter. Also, the native version is so much faster that a separate test would have to be done to get more accurate results for the other test cases :)

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 is the most efficient way of creating an HTML element and appending attributes to it and then wrapping it inside of another element?

jQuery not needed.

document.getElementById("screenshots").insertAdjacentHTML("beforeend", 
'<a href="' + link + '" title="' + title + '">\n\
<img src="' + el + '" alt="" width="200px" height="200px">\n\
</a>'
);

Most efficient way to update a bunch of HTML elements with jQuery / JavaScript?

jQuery templates used to be a thing, but you might also check out this discussion about other options. Backbone is a popular library for this, but as you'll discover there are plenty of alternatives.

In short, it sounds like a template library is going to be a far cleaner solution than manually updating HTML through jQuery.

Most efficient way to create an element from any jquery selector string

Ive created a plugin to solve the problem.

$("a.exaggerated#selector[data-myattr='data-here']").create().appendTo('body');

jquery version 2.1.1 and obove is required to access the $.find.tokenize method

$.fn.create = function( elem, dataAndEvents, deepDataAndEvents ) { 

if(this.length){

return $(this).clone( elem, dataAndEvents, deepDataAndEvents );

} else {

var selector = this.selector;
var rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/;
var match, elem, m;

if(!selector){
return $(document.createElement('div'));
}
if(match = rquickExpr.exec( selector )){

if ( match[2] ) {
return $(document.createElement(selector));
} else {

var elem = document.createElement('div');
if ( (m = match[1]) ) {
elem.id = m;
} else if ( (m = match[3])) {
elem.className = m ;
}
return $(elem);
}
}
selector = selector.replace( rtrim, "$1" );
match = $.find.tokenize(selector);

if ( match.length === 1 ) {

var attrs = '';
var tag = 'div';
var classList = [];
var type, value, matches;
var tokens = match[0] = match[0].slice( 0 );

for (var i = 0; i < tokens.length; i++) {

type = tokens[i].type;
value = tokens[i].value
matches = tokens[i].matches;

if ( type === "ID" ){
attrs += 'id="' + matches[0] + '" ';
continue;
}
else if ( type === "CLASS" ){
classList.push(matches[0]+matches[1]+matches[2]);
continue;
}
else if ( type === "TAG" ){
tag = matches[0];
continue;
}
else if ( type === "ATTR" ){
attrs += matches[0]+ (matches[1] ? matches[1] : '' ) + (matches[2] ? '"' + matches[2] + '"': '' )+ ' ';
}
else if ( type === "PSEUDO" ){

}
else if ( type === "CHILD" ){

}
};

if(classList.length){
attrs += 'class="';
for (var i = 0; i < classList.length; i++) {
attrs += classList[i] + ' ';
};
attrs += '"';
}
return $('<' + tag + ' ' + attrs + '></' + tag + '>');
}
return $(document.createElement('div'));
}
}

jQuery: Most efficient way to create blocks of HTML based on number of selected items?

The most efficient method may vary across browsers, but I would imagine that setting the innerHTML of a <ul> with a string of html elements would offer the best performance.

Here's a Working Demo

$("#select").change(function() {
var val = this.value,
lis = '';

for(var i=1; i <= val; i++) {
lis += '<li> Ticket ' + i + '</li>';
}

document.getElementById('list').innerHTML = lis;
});

and HTML

  <select id="select">
<option value="1">1 ticket</option>
<option value="2">2 tickets</option>
<option value="3">3 tickets</option>
<option value="4">4 tickets</option>
<option value="5">5 tickets</option>
<option value="6">6 tickets</option>
</select>

<ul id="list"></ul>

How to build a complex HTML dynamically using jquery

You could use append() like :

var container_div = $("<div>", {"style" : "background-color: #757575;border: 1px solid gray;"});
var table = $("<table>", {"style" : "width: 100%; height: 100%"}).append("<tr><td><table style='width: 100%; background-color: #757575; color: white" + ";border-bottom:1px solid black;height:25px;table-layout:fixed'>" + "<tr>" + "<td nowrap style='width: 70px; background-color: #999999; font-weight: bold; color: black'>ID</td>" + "<td style='width:100px;background-color: #999999; font-weight: bold; color: black'>Name</td>" + "<td style='text-align:left;width: 90px; background-color: #999999; font-weight: bold; color: black'>Status</td>" + "</tr>" + "</table></td></tr>");
container_div.append(table);$("#MainDiv").append(container_div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="MainDiv"></div>


Related Topics



Leave a reply



Submit