JQuery - best practice for creating complex HTML snippets

Is there a general practice for creating multiple complex HTML elements in jQuery? I tried several different ways.

At first I tried using createElement and linking a lot of them together with AppendTo and the like:

var badge = $(document.createElement("div")).attr("class", "wrapper1").appendTo("body"); $(document.createElement("div")).attr("class", "wrapper2").appendTo(".wrapper1"); $(document.createElement("table")).attr("class", "badgeBody").appendTo(".wrapper2"); $(document.createElement("tr")).attr("class", "row1").appendTo(".badgeBody"); $(document.createElement("td")).appendTo(".row1"); $(document.createElement("span")).attr("class", "badgeUnlocked").text("UNLOCKED! ").appendTo("td"); $(document.createElement("td")).attr("class", "badgeTitleText").appendTo(".row1"); $(document.createElement("span")).attr("class", "badgeTitle").text(name).appendTo(".badgeTitleText"); $(document.createElement("tr")).attr("class", "row2").appendTo(".badgeBody"); $(document.createElement("td")).appendTo(".row2"); $(document.createElement("img")).attr("src", imgUrl).appendTo(".row2 td"); $(document.createElement("td")).attr("class", "badgeText").appendTo(".row2"); $(document.createElement("span")).attr("class", "badgeDescription").text(description).appendTo(".badgeText"); 

This can be rude, because appendTo wants to add to each corresponding element so that everything needs its own name, otherwise it will be constantly added throughout the place.

Then I tried to create an array and merge it:

 var badgeFragment = [ '<div><div id="'+ closeId+'" class="closeTab">X</div>', '<div id="'+ badgeId+'" class="wrapper1">', '<div class="wrapper2">', '<div class="badgeBody">', '<div class="badgeImage">', '<img src="'+ imgUrl +'">', '</div>', '<div class="badgeContents">', '<div class="badgeUnlocked">ACHIEVEMENT UNLOCKED: </div>', '<div class="badgeTitle">'+ name +'</div>', '<div id="'+ textId+'" class="badgeDescription">'+ description +'</div>', '</div>', '<div style="clear:both"></div>', '</div></div></div></div></div>', ] badgeFragment = $(badgeFragment.join('')); 

This works very well, although in IE, when I put a warning ($ (badgeFragment) .text ()), it usually returned empty. (This was part of debugging a larger problem). I'm obviously a little new to jQuery (and even Javascript), so to try to make sure this is not a problem, I tried the third method - giant string concatenation:

 var badgeFragment = '<div><div id="'+ closeId+'" class="closeTab">X</div>' + '<div id="'+ badgeId+'" class="wrapper1">' + '<div class="wrapper2">' + '<div class="badgeBody">' + '<div class="badgeImage">' + '<img src="C:/Users/Ryan/Documents/icons/crystal_project/64x64/apps/chat.png">' + '</div>' + '<div class="badgeContents">' + '<div class="badgeUnlocked">ACHIEVEMENT UNLOCKED: </div>' + '<div class="badgeTitle">test</div>' + '<div id="'+ textId+'" class="badgeDescription">test</div>' + '</div>' + '<div style="clear:both"></div>' + '</div></div></div></div></div>'; 

Is one of these methods better than the other? I'm not very good at various profilers, so I'm not sure how to check this. There is also the question of whether or not all of these methods are compatible with the browser.

+47
jquery html
Feb 07 '10 at 16:46
source share
8 answers

With jQuery 1.4, you can create HTML elements as follows:

 // create an element with an object literal, defining properties var e = $("<a />", { href: "#", "class": "a-class another-class", // you need to quote "class" since it a reserved keyword title: "..." }); // add the element to the body $("body").append(e); 

Here is a link to the documentation .

I am not sure if this approach is faster than using the html() jQuery function. Or faster than skipping jQuery all together and using the innerHTML property for the element. But as for readability; The jQuery approach is my favorite. And in most cases, the performance gain when using innerHTML is negligible.

+56
Feb 07 '10 at 17:07
source share

You do not need to call document.createElement:

 $('#existingContainer').append( $('<div/>') .attr("id", "newDiv1") .addClass("newDiv purple bloated") .append("<span/>") .text("hello world") ); 

JQuery has all sorts of useful tools for expanding / changing the DOM. Look at the various "wrap" methods, for example.

Another possibility: for really big drops of new content, you might be better off if your server prepares them (using a server-side template system, whatever you do) and fetching using $.load() or another ajax approach.

+8
Feb 07 2018-10-07T00
source share

I would be inclined to look at one of the templates for jquery like jQote

+8
Feb 07 2018-10-17T00
source share

John Resig (creator of jQuery) suggested using this template method back in 2008. In fact, it had rather interesting functions:

 <script type="text/html" id="item_tmpl"> <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>"> <div class="grid_1 alpha right"> <img class="righted" src="<%=profile_image_url%>"/> </div> <div class="grid_6 omega contents"> <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p> </div> </div> </script> 

then extracting it using ...

 var results = document.getElementById("results"); results.innerHTML = tmpl("item_tmpl", dataObject); 

See here for full details:
http://ejohn.org/blog/javascript-micro-templating/

+7
Sep 01 2018-11-11T00:
source share

I personally think that reading and editing is more important for code than execution. Regardless of the fact that it’s easier for you to watch and make changes without breaking it, there should be one that you choose.

+3
Feb 07 2018-10-07T00
source share

I like the template language Handlebars.js

+3
Apr 14 '14 at 16:36
source share

This is more readable and maintainable if the JavaScript code is similar to the HTML tag structure. You can go to the official jQuery route using $ ('div', {'class': 'etc'}) ...

Here is a slightly different approach using the $$ function so that each element edits a jQuery object. This should be pretty fast since there is no parsing html.

 $$('div', {'id':'container'}, $$('div', {'id':'my_div'}, $$('h1',{'class':'my_header'}, $$('a',{'href':'/test/', 'class':'my_a_class'}, 'teststring')))); 

This makes the approach more flexible, and you can add event handlers, data, etc. to jQuery nested objects using chaining is pretty easy, for example.

 $$('div', {'id':'container'}, $$('div', {'id':'my_div'}, $$('h1',{'class':'my_header'}, $$('a', { 'href': '/test/', 'class': 'my_a_class' }, 'teststring') ).click(function() { alert('clicking on the header'); }) ).data('data for the div') ).hide(); 

The code is more readable than if the official jQuery approach was used to execute it with separate calls .append () ,. text () ,. html (), etc. or by submitting jQuery $ concatenated HTML string.

Reference function $$:

 function $$(tagName, attrTextOrElems) { // Get the arguments coming after the params argument var children = []; for (var _i = 0; _i < (arguments.length - 2) ; _i++) { children[_i] = arguments[_i + 2]; } // Quick way of creating a javascript element without JQuery parsing a string and creating the element var elem = document.createElement(tagName); var $elem = $(elem); // Add any text, nested jQuery elements or attributes if (attrTextOrElems) { if (typeof attrTextOrElems === "string") { // text var text = document.createTextNode(attrTextOrElems); elem.appendChild(text); } else if (attrTextOrElems instanceof jQuery) { // JQuery elem $elem.append(attrTextOrElems); } else // Otherwise an object specifying attributes eg { 'class': 'someClass' } { for (var key in attrTextOrElems) { var val = attrTextOrElems[key]; if (val) { elem.setAttribute(key, val); } } } } // Add any further child elements or text if (children) { for (var i = 0; i < children.length; i++) { var child = children[i]; if (typeof child === "string") { // text var text = document.createTextNode(child); elem.appendChild(text); } else { // JQuery elem $elem.append(child); } } } return $elem; } 
+2
Oct 10 '16 at 21:50
source share

The way I do is shown below. I'm not sure that u should create so many divs, but it worked very well with me.

 var div1 = $('<div class="colwrap_fof"></div>'); //THE COMPLEX DIV ITSELF var div2 = $('<div class="homeimg"></div>'); var div21 = $('<div id="backImageDiv'+fof_index+'" class="backDiv"></div>'); var div22 = $('<div id="frontImageDiv'+fof_index+'" class="frontDiv"></div>'); div2.append(div21); div2.append(div22); div1.append(div2); $("#df_background").append(div1); // ADDING the complex div to the right place 

Greetings

0
Jan 05 '13 at
source share



All Articles