Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearest way to build html elements in jQuery

I've seen a lot of different styles (and few different methods) of creating elements in jQuery. I was curious about the clearest way to build them, and also if any particular method is objectively better than another for any reason. Below are some examples of the styles and methods that I've seen.

var title = "Title"; var content = "Lorem ipsum";  // escaping endlines for a multi-line string // (aligning the slashes is marginally prettier but can add a lot of whitespace) var $element1 = $("\     <div><h1>" + title + "</h1>\         <div class='content'>  \         " + content + "        \         </div>                 \     </div>                     \ ");  // all in one // obviously deficient var $element2 = $("<div><h1>" + title + "</h1><div class='content'>" + content + "</div></div>");  // broken on concatenation var $element3 = $("<div><h1>" +                 title +                  "</h1><div class='content'>" +                 content +                 "</div></div>");  // constructed piecewise // (I've seen this with nested function calls instead of temp variables) var $element4 = $("<div></div>"); var $title = $("<h1></h1>").html(title); var $content = $("<div class='content'></div>").html(content); $element4.append($title, $content);  $("body").append($element1, $element2, $element3, $element4); 

Please feel free to demonstrate any other methods/styles you might use.

like image 794
bkconrad Avatar asked Mar 18 '12 17:03

bkconrad


People also ask

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

Conclusion: The $(document. createElement('div')); is the fastest method, even the benchmarking supports, this is the fastest technique to create an HTML element using jQuery.

How HTML element is used in jQuery?

jQuery html() MethodThe html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.

What does $$ mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.


2 Answers

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")); 
like image 73
Baer Avatar answered Oct 13 '22 21:10

Baer


After looking around for a while, I found the style which I finally settled on. First, I'll say that I used Mustache for templating, and it worked well. Sometimes, though, you just need to build an element one time, without reusing it, or have some other motivation to not bring in another library. In this situation, I have taken to using:

$("body") .append(     $("<div>")     .append(         $("<div>")         .append(             $("<h1>").text(title)         )     )     .append(         $("<div>").text(content)     ) );​ 

This works because append() returns a reference to the object you're appending to, so chained append()s attach to the same object. With proper indentation, the structure of the markup is obvious, and this way it's easy to modify. Obviously this is slower than using templates (the whole thing has to be built piece by piece), but if you're only using it for initialization or something similar then it is a great compromise.

There are many ways one could format a construct like this, but I've chosen a way to make it clear what's going on. The rule I used is that there should be a maximum of one opening parenthesis and/or one closing parenthesis on each line. Also, the leaves of these append trees do not need to be passed to the jQuery constructor, but I've done so here for visual repetition.

like image 25
bkconrad Avatar answered Oct 13 '22 21:10

bkconrad