The preferred way of creating a new element with jQuery

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?


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

链接地址: http://www.djcxy.com/p/14608.html

上一篇: JS:什么时候元素变得可见的事件监听器?

下一篇: 用jQuery创建新元素的首选方法