admin管理员组

文章数量:1129017

I've got 2 ways I can create a <div> using jQuery.

Either:

var div = $("<div></div>");
$("#box").append(div);

Or:

$("#box").append("<div></div>");

What are the drawbacks of using second way other than re-usability?

I've got 2 ways I can create a <div> using jQuery.

Either:

var div = $("<div></div>");
$("#box").append(div);

Or:

$("#box").append("<div></div>");

What are the drawbacks of using second way other than re-usability?

Share Improve this question edited Apr 4, 2017 at 9:39 Cœur 38.6k26 gold badges202 silver badges276 bronze badges asked May 16, 2012 at 13:21 AshwinAshwin 12.4k22 gold badges84 silver badges119 bronze badges 10
  • 9 It's just matter of reusability. Your call. – Roko C. Buljan Commented May 16, 2012 at 13:22
  • @gdoron by reusability I mean : if you have an element inside a variable, than you can re-call that var wherever you need, just like in your example. – Roko C. Buljan Commented May 16, 2012 at 13:24
  • 2 Why .html, but not .append in 2nd case? – Engineer Commented May 16, 2012 at 13:26
  • @Engineer - Sorry, that was mistake here. I corrected that. – Ashwin Commented May 16, 2012 at 13:27
  • I thought the latter method was faster in terms of speed execution but the first one seems (10% ~ 40%) faster: jsperf.com/jquery-append-string-vs-append-jquery-reference – Fabrizio Calderan Commented May 16, 2012 at 13:34
 |  Show 5 more comments

8 Answers 8

Reset to default 386

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.

I personally think that it's more important for the code to be readable and editable than performant. Whichever one you find easier to look at and it should be the one you choose for above factors. You can write it as:

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

And your first Method as:

// create an element with an object literal, defining properties
var $e = $("<div>", {id: "newDiv1", name: 'test', class: "aClass"});
$e.click(function(){ /* ... */ });
// add the element to the body
$("#box").append($e);

But as far as readability goes; the jQuery approach is my favorite. Follow this Helpful jQuery Tricks, Notes, and Best Practices

Much more expressive way,

jQuery('<div/>', {
    "id": 'foo',
    "name": 'mainDiv',
    "class": 'wrapper',
    "click": function() {
      jQuery(this).toggleClass("test");
    }}).appendTo('selector');

Reference: Docs

Be sure to read the docs thoroughly, as this notation has certain consequences that won't be immediately obvious to the person inspecting the code.

The name "class" must be quoted in the object since it is a JavaScript reserved word, and "className" cannot be used since it refers to the DOM property, not the attribute. While the second argument is convenient, its flexibility can lead to unintended consequences (e.g. $( "<input>", {size: "4"} ) calling the .size() method instead of setting the size attribute).

According to the jQuery official documentation

To create a HTML element, $("<div/>") or $("<div></div>") is preferred.

Then you can use either appendTo, append, before, after and etc,. to insert the new element to the DOM.

PS: jQuery Version 1.11.x

According to the documentation for 3.4, It is preferred to use attributes with attr() method.

$('<div></div>').attr(
  {
    id: 'some dynanmic|static id',
    "class": 'some dynanmic|static class'
  }
).click(function() {
  $( "span", this ).addClass( "bar" ); // example from the docs
});

It is also possible to create a div element in the following way:

var my_div = document.createElement('div');

add class

my_div.classList.add('col-10');

also can perform append() and appendChild()

I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.

If #box is empty, nothing, but if it's not these do very different things. The former will add a div as the last child node of #box. The latter completely replaces the contents of #box with a single empty div, text and all.

本文标签: javascriptThe preferred way of creating a new element with jQueryStack Overflow