简体   繁体   中英

jQuery adding element to the DOM: the right way

I'm wondering which approach is better and why:

a)

  .append('<div class="load" id="XXX"></div>)

b)

  .append('<div></div>').addClass('load').attr('id', 'XXX')

c)

   your way

As of jQuery 1.4 you can pass a map object as a second parameter

$('<li/>', { 
  click:    function(){}, 
  id:       'test',
  addClass: 'clickable' 
});

I find this method much more readable than having a single string or many jQuery method calls and chaining.

Check the docs here . Some issues with IE for input elements.

Anyway both when using jQuery or basic JavaScript, creating an element and its attributes in a string is discouraged. Better to separate the creation and the attribution of the attributes.

I created a fiddle for a direct comparison of the 3 jQuery methods, plus a pure JavaScript one.

While both the new 1.4 option and the usual one are pretty fast, the string method is slow as hell. This is no surprise since jQuery has to parse and interpret it all.

Of course, pure JS is always the fastest option ;)

This is how I normally handle it using jQuery. I find it more readable, but that is just preference.

var newdiv = $('<div></div>');

newdiv
  .addClass('load')
  .attr('id', 'XXX');

$('#someElement').append(newdiv);

I like to create elements the old fashioned way

var aDiv = document.createElement("div");
aDiv.id="blah";
aDiv.className+="meh ";
document.body.appendChild(aDiv);

as to what's better though? no idea.

新的答案,我经历并更新了某人的jsPerf测试,所以它实际上工作,似乎其他人是对的,我错了: http//jsperf.com/document-write-vs-document-createelement/4/

var div = $('<div class="load" id="test"></div>');
.append(div);

The first method is the "best" in that it is the fastest because it minimizes the underlying DOM operations. Obviously as the element gets more complicated, constructing with jQuery methods gets more convenient and your definition of "best" might change.

Another option (even though it's a little more code to type but way cleaner in my opinion), is to use JAML . Example:

Jaml.register('new-div', function() {
  div({class:'load', id:'XXX'})
});

Once it's registered, it's super easy to render on the page:

$("#element-to-append-to").append( Jaml.render("new-div") );

Like I said, slightly more code to type, but once you have all these templates rendered it's incredibly easy to re-use the templates elsewhere.

This has turned into more of an opinion question than an actual question that will have an answer, however I will give my opinion anyway.

I prefer to build the html as a string first, then pass it into jquery to turn it into html. For example,

function buildDiv(obj){
  var str = [
    '<div id="',obj.id,'" class="',obj.class,'">',
      obj.content,
    '</div>'
  ].join("");
  return str;
}
$(buildDiv({
  id: "foo",
  class: "bar",
  content: "Test Content!"
}).appendTo(target);

I know that is overkill for creating a simple div, however it's very useful when you have to create a collection of something, such as turning an array into an ordered list. This is basically the same thing as doing

$("<div id='foo' class='bar'></div>");

only i used a function to generate the string. This allows me to modify the function, then use the same function elsewhere to build other strings that need to follow the same template.

What you consider "best" may vary from situation to situation based on the needs of the project.

I will however say it is much better(faster) to manipulate html before you append it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM