The preferred way of creating a new element with jQuery


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


var div = $("<div></div>");



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

4/4/2017 9:39:43 AM

Accepted Answer

The first option gives you more flexibilty:

var $div = $("<div>", {id: "foo", "class": "a"});
${ /* ... */ });

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.

5/23/2017 11:33:26 AM

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:

    .attr("id", "newDiv1")
    .addClass("newDiv purple bloated")
      .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"});
${ /* ... */ });
// add the element to the body

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

Reference: Docs


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.

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

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.