The preferred way of creating a new element with jQuery
Asked Answered
U

8

258

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?

Untouched answered 16/5, 2012 at 13:21 Comment(10)
It's just matter of reusability. Your call.Sterculiaceous
@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.Sterculiaceous
Why .html, but not .append in 2nd case?Standifer
@Standifer - Sorry, that was mistake here. I corrected that.Untouched
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-referenceZeal
@F.Calderan. You read it wrong, "operations per second (higher is better)". And should test it with more complex elements than a blank div.Wimberly
to me the first one makes 8000 ops/sec, the second 4900 ops/sec => the first is faster. anyway I will try to add more markup :)Zeal
@F.Calderan. check thisWimberly
possible duplicate of Creating a div element in jQueryMow
The first one is a low level programmatic builder approach (fast). The second can be complex html as string which is parsed (expensive).Phenix
W
383

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.

Wimberly answered 16/5, 2012 at 13:22 Comment(7)
Also a good practice to start jQuery collection names with a "$", in my opinion. Just noting that what you've done does not require $div: $("<div>", {id: 'foo', class: 'a', click: function () {}}).appendTo("#box");Kallick
Are those dollar signs necessary or a typo? $div. I haven't seen that syntax before, but I'm new to Jquery.Bandaranaike
I always use the $ is the variable is a jquery object, $_ if it is a jQuery collection, and _var if it is a counter. The var for regular variables.Kenneth
where is the documentation for this way of creating element? $("<div>", {id: "foo", class: "a"});. I want to know if there are other options for itPneumatophore
@Wimberly please, take a look at my question #35413544Gillan
why is the id key without quotes whereas the class key requires quotesKobe
@codemonkey class is a reserved keyword in JavaScript while id is not. Hence the difference. See javascripter.net/faq/reserved.htmWimberly
B
88

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

Blouin answered 16/5, 2012 at 13:43 Comment(2)
Thanks for that link to the jQuery reference on creating new HTML elements. SO hard to google for that.Craig
Better do it like: https://mcmap.net/q/45146/-creating-a-div-element-in-jquery-duplicateSterculiaceous
D
29

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

Dun answered 8/7, 2013 at 7:54 Comment(1)
class should be in quotes, according to the docs (via Docs link above): "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."Myth
B
7

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

Blood answered 9/4, 2015 at 17:36 Comment(0)
N
5

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
});
Northumbria answered 24/2, 2020 at 12:46 Comment(1)
I added quotes. If you don't put class in quotes, this will silently fail and may result in insanity.Trichromat
C
0

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.

Cloutman answered 16/5, 2012 at 13:23 Comment(1)
@Ash with the second approach, you may mistakenly wipe out all of the other children of the container you are modifying: jsfiddle.net/jbabey/RBXq5/1Cloutman
K
0

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.

Kallick answered 16/5, 2012 at 13:25 Comment(1)
Oh .. I mean't to use append here ;)Untouched
A
0

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

Archerfish answered 29/7, 2017 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.