[javascript] 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?

This question is related to javascript jquery append createelement jquery-append

The answer is


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


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.


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()


Much more expressive way,

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

Reference: Docs


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


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to append

List append() in for loop ValueError: all the input arrays must have same number of dimensions Append a tuple to a list - what's the difference between two ways? How merge two objects array in angularjs? How to add an element at the end of an array? Appending a list or series to a pandas DataFrame as a row? Can someone explain how to append an element to an array in C programming? How to append elements at the end of ArrayList in Java? Append value to empty vector in R? How to append new data onto a new line

Examples related to createelement

Creating a div element inside a div element in javascript The preferred way of creating a new element with jQuery Javascript Append Child AFTER Element

Examples related to jquery-append

The preferred way of creating a new element with jQuery How to add a list item to an existing unordered list? Creating a div element in jQuery