[javascript] jQuery document.createElement equivalent?

I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.

var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;

var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);

I would like to know if there is a better way to do this using jQuery. I've been experimenting with:

var odv = $.create("div");
$.append(odv);
// And many more

But I'm not sure if this is any better.

This question is related to javascript jquery html dom dhtml

The answer is


Here's your example in the "one" line.

this.$OuterDiv = $('<div></div>')
    .hide()
    .append($('<table></table>')
        .attr({ cellSpacing : 0 })
        .addClass("text")
    )
;

Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about $("<div>") vs $("<div></div>") vs $(document.createElement('div')) as a way of creating new elements, and which is "best".

I put together a small benchmark, and here are roughly the results of repeating the above options 100,000 times:

jQuery 1.4, 1.5, 1.6

               Chrome 11  Firefox 4   IE9
<div>            440ms      640ms    460ms
<div></div>      420ms      650ms    480ms
createElement    100ms      180ms    300ms

jQuery 1.3

                Chrome 11
<div>             770ms
<div></div>      3800ms
createElement     100ms

jQuery 1.2

                Chrome 11
<div>            3500ms
<div></div>      3500ms
createElement     100ms

I think it's no big surprise, but document.createElement is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.


Update 2

Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!

http://jsben.ch/#/ARUtz


var mydiv = $('<div />') // also works

Creating new DOM elements is a core feature of the jQuery() method, see:


It's all pretty straight forward! Heres a couple quick examples...


var $example = $( XMLDocRoot );

var $element = $( $example[0].createElement('tag') );
// Note the [0], which is the root

$element.attr({
id: '1',
hello: 'world'
});

var $example.find('parent > child').append( $element );

Not mentioned in previous answers, so I'm adding working example how to create element elements with latest jQuery, also with additional attributes like content, class, or onclick callback:

_x000D_
_x000D_
const mountpoint = 'https://jsonplaceholder.typicode.com/users'_x000D_
_x000D_
const $button = $('button')_x000D_
const $tbody = $('tbody')_x000D_
_x000D_
const loadAndRender = () => {_x000D_
  $.getJSON(mountpoint).then(data => {_x000D_
_x000D_
    $.each(data, (index, { id, username, name, email }) => {_x000D_
      let row = $('<tr>')_x000D_
        .append($('<td>', { text: id }))_x000D_
        .append($('<td>', {_x000D_
          text: username,_x000D_
          class: 'click-me',_x000D_
          on: {_x000D_
            click: _ => {_x000D_
              console.log(name)_x000D_
            }_x000D_
          }_x000D_
        }))_x000D_
        .append($('<td>', { text: email }))_x000D_
_x000D_
      $tbody.append(row)_x000D_
    })_x000D_
_x000D_
  })_x000D_
}_x000D_
_x000D_
$button.on('click', loadAndRender)
_x000D_
.click-me {_x000D_
  background-color: lightgrey_x000D_
}
_x000D_
<table style="width: 100%">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>ID</th>_x000D_
      <th>Username</th>_x000D_
      <th>Email</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
  _x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<button>Load and render</button>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
_x000D_
_x000D_
_x000D_


Creating new DOM elements is a core feature of the jQuery() method, see:


Though this is a very old question, I thought it would be nice to update it with recent information;

Since jQuery 1.8 there is a jQuery.parseHTML() function which is now a preferred way of creating elements. Also, there are some issues with parsing HTML via $('(html code goes here)'), fo example official jQuery website mentions the following in one of their release notes:

Relaxed HTML parsing: You can once again have leading spaces or newlines before tags in $(htmlString). We still strongly advise that you use $.parseHTML() when parsing HTML obtained from external sources, and may be making further changes to HTML parsing in the future.

To relate to the actual question, provided example could be translated to:

this.$OuterDiv = $($.parseHTML('<div></div>'))
    .hide()
    .append($($.parseHTML('<table></table>'))
        .attr({ cellSpacing : 0 })
        .addClass("text")
    )
;

which is unfortunately less convenient than using just $(), but it gives you more control, for example you may choose to exclude script tags (it will leave inline scripts like onclick though):

> $.parseHTML('<div onclick="a"></div><script></script>')
[<div onclick=?"a">?</div>?]

> $.parseHTML('<div onclick="a"></div><script></script>', document, true)
[<div onclick=?"a">?</div>?, <script>?</script>?]

Also, here's a benchmark from the top answer adjusted to the new reality:

JSbin Link

jQuery 1.9.1

  $.parseHTML:    88ms
  $($.parseHTML): 240ms
  <div></div>:    138ms
  <div>:          143ms
  createElement:  64ms

It looks like parseHTML is much closer to createElement than $(), but all the boost is gone after wrapping the results in a new jQuery object


jQuery out of the box doesn't have the equivalent of a createElement. In fact the majority of jQuery's work is done internally using innerHTML over pure DOM manipulation. As Adam mentioned above this is how you can achieve similar results.

There are also plugins available that make use of the DOM over innerHTML like appendDOM, DOMEC and FlyDOM just to name a few. Performance wise the native jquery is still the most performant (mainly becasue it uses innerHTML)


I've just made a small jQuery plugin for that: https://github.com/ern0/jquery.create

It follows your syntax:

var myDiv = $.create("div");

DOM node ID can be specified as second parameter:

var secondItem = $.create("div","item2");

Is it serious? No. But this syntax is better than $("<div></div>"), and it's a very good value for that money.

I'm a new jQuery user, switching from DOMAssistant, which has a similar function: http://www.domassistant.com/documentation/DOMAssistantContent-module.php

My plugin is simpler, I think attrs and content is better to add by chaining methods:

$("#container").append( $.create("div").addClass("box").html("Hello, world!") );

Also, it's a good example for a simple jQuery-plugin (the 100th one).


What about this, for example when you want to add a <option> element inside a <select>

$('<option/>')
  .val(optionVal)
  .text('some option')
  .appendTo('#mySelect')

You can obviously apply to any element

$('<div/>')
  .css('border-color', red)
  .text('some text')
  .appendTo('#parentDiv')

var mydiv = $('<div />') // also works

var div = $('<div/>');
div.append('Hello World!');

Is the shortest/easiest way to create a DIV element in jQuery.


Not mentioned in previous answers, so I'm adding working example how to create element elements with latest jQuery, also with additional attributes like content, class, or onclick callback:

_x000D_
_x000D_
const mountpoint = 'https://jsonplaceholder.typicode.com/users'_x000D_
_x000D_
const $button = $('button')_x000D_
const $tbody = $('tbody')_x000D_
_x000D_
const loadAndRender = () => {_x000D_
  $.getJSON(mountpoint).then(data => {_x000D_
_x000D_
    $.each(data, (index, { id, username, name, email }) => {_x000D_
      let row = $('<tr>')_x000D_
        .append($('<td>', { text: id }))_x000D_
        .append($('<td>', {_x000D_
          text: username,_x000D_
          class: 'click-me',_x000D_
          on: {_x000D_
            click: _ => {_x000D_
              console.log(name)_x000D_
            }_x000D_
          }_x000D_
        }))_x000D_
        .append($('<td>', { text: email }))_x000D_
_x000D_
      $tbody.append(row)_x000D_
    })_x000D_
_x000D_
  })_x000D_
}_x000D_
_x000D_
$button.on('click', loadAndRender)
_x000D_
.click-me {_x000D_
  background-color: lightgrey_x000D_
}
_x000D_
<table style="width: 100%">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>ID</th>_x000D_
      <th>Username</th>_x000D_
      <th>Email</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
  _x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<button>Load and render</button>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
_x000D_
_x000D_
_x000D_


since jQuery1.8, using $.parseHTML() to create elements is a better choice.

there are two benefits:

1.if you use the old way, which may be something like $(string), jQuery will examine the string to make sure you want to select a html tag or create a new element. By using $.parseHTML(), you tell jQuery that you want to create a new element explicitly, so the performance may be a little better.

2.much more important thing is that you may suffer from cross site attack (more info) if you use the old way. if you have something like:

    var userInput = window.prompt("please enter selector");
    $(userInput).hide();

a bad guy can input <script src="xss-attach.js"></script> to tease you. fortunately, $.parseHTML() avoid this embarrassment for you:

var a = $('<div>')
// a is [<div>?</div>?]
var b = $.parseHTML('<div>')
// b is [<div>?</div>?]
$('<script src="xss-attach.js"></script>')
// jQuery returns [<script src=?"xss-attach.js">?</script>?]
$.parseHTML('<script src="xss-attach.js"></script>')
// jQuery returns []

However, please notice that a is a jQuery object while b is a html element:

a.html('123')
// [<div>?123?</div>?]
b.html('123')
// TypeError: Object [object HTMLDivElement] has no method 'html'
$(b).html('123')
// [<div>?123?</div>?]

I've just made a small jQuery plugin for that: https://github.com/ern0/jquery.create

It follows your syntax:

var myDiv = $.create("div");

DOM node ID can be specified as second parameter:

var secondItem = $.create("div","item2");

Is it serious? No. But this syntax is better than $("<div></div>"), and it's a very good value for that money.

I'm a new jQuery user, switching from DOMAssistant, which has a similar function: http://www.domassistant.com/documentation/DOMAssistantContent-module.php

My plugin is simpler, I think attrs and content is better to add by chaining methods:

$("#container").append( $.create("div").addClass("box").html("Hello, world!") );

Also, it's a good example for a simple jQuery-plugin (the 100th one).


I'm doing like that:

$('<div/>',{
    text: 'Div text',
    class: 'className'
}).appendTo('#parentDiv');

Simply supplying the HTML of elements you want to add to a jQuery constructor $() will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's append() method.

For example:

var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);

You could then populate this table programmatically, if you wished.

This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using createElement and then setting attributes like cellSpacing and className via JS.


What about this, for example when you want to add a <option> element inside a <select>

$('<option/>')
  .val(optionVal)
  .text('some option')
  .appendTo('#mySelect')

You can obviously apply to any element

$('<div/>')
  .css('border-color', red)
  .text('some text')
  .appendTo('#parentDiv')

Simply supplying the HTML of elements you want to add to a jQuery constructor $() will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's append() method.

For example:

var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);

You could then populate this table programmatically, if you wished.

This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using createElement and then setting attributes like cellSpacing and className via JS.


var div = $('<div/>');
div.append('Hello World!');

Is the shortest/easiest way to create a DIV element in jQuery.


It's all pretty straight forward! Heres a couple quick examples...


var $example = $( XMLDocRoot );

var $element = $( $example[0].createElement('tag') );
// Note the [0], which is the root

$element.attr({
id: '1',
hello: 'world'
});

var $example.find('parent > child').append( $element );

jQuery out of the box doesn't have the equivalent of a createElement. In fact the majority of jQuery's work is done internally using innerHTML over pure DOM manipulation. As Adam mentioned above this is how you can achieve similar results.

There are also plugins available that make use of the DOM over innerHTML like appendDOM, DOMEC and FlyDOM just to name a few. Performance wise the native jquery is still the most performant (mainly becasue it uses innerHTML)


Simply supplying the HTML of elements you want to add to a jQuery constructor $() will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's append() method.

For example:

var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);

You could then populate this table programmatically, if you wished.

This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using createElement and then setting attributes like cellSpacing and className via JS.


jQuery out of the box doesn't have the equivalent of a createElement. In fact the majority of jQuery's work is done internally using innerHTML over pure DOM manipulation. As Adam mentioned above this is how you can achieve similar results.

There are also plugins available that make use of the DOM over innerHTML like appendDOM, DOMEC and FlyDOM just to name a few. Performance wise the native jquery is still the most performant (mainly becasue it uses innerHTML)


UPDATE

As of the latest versions of jQuery, the following method doesn't assign properties passed in the second Object

Previous answer

I feel using document.createElement('div') together with jQuery is faster:

$(document.createElement('div'), {
    text: 'Div text',
    'class': 'className'
}).appendTo('#parentDiv');

since jQuery1.8, using $.parseHTML() to create elements is a better choice.

there are two benefits:

1.if you use the old way, which may be something like $(string), jQuery will examine the string to make sure you want to select a html tag or create a new element. By using $.parseHTML(), you tell jQuery that you want to create a new element explicitly, so the performance may be a little better.

2.much more important thing is that you may suffer from cross site attack (more info) if you use the old way. if you have something like:

    var userInput = window.prompt("please enter selector");
    $(userInput).hide();

a bad guy can input <script src="xss-attach.js"></script> to tease you. fortunately, $.parseHTML() avoid this embarrassment for you:

var a = $('<div>')
// a is [<div>?</div>?]
var b = $.parseHTML('<div>')
// b is [<div>?</div>?]
$('<script src="xss-attach.js"></script>')
// jQuery returns [<script src=?"xss-attach.js">?</script>?]
$.parseHTML('<script src="xss-attach.js"></script>')
// jQuery returns []

However, please notice that a is a jQuery object while b is a html element:

a.html('123')
// [<div>?123?</div>?]
b.html('123')
// TypeError: Object [object HTMLDivElement] has no method 'html'
$(b).html('123')
// [<div>?123?</div>?]

Though this is a very old question, I thought it would be nice to update it with recent information;

Since jQuery 1.8 there is a jQuery.parseHTML() function which is now a preferred way of creating elements. Also, there are some issues with parsing HTML via $('(html code goes here)'), fo example official jQuery website mentions the following in one of their release notes:

Relaxed HTML parsing: You can once again have leading spaces or newlines before tags in $(htmlString). We still strongly advise that you use $.parseHTML() when parsing HTML obtained from external sources, and may be making further changes to HTML parsing in the future.

To relate to the actual question, provided example could be translated to:

this.$OuterDiv = $($.parseHTML('<div></div>'))
    .hide()
    .append($($.parseHTML('<table></table>'))
        .attr({ cellSpacing : 0 })
        .addClass("text")
    )
;

which is unfortunately less convenient than using just $(), but it gives you more control, for example you may choose to exclude script tags (it will leave inline scripts like onclick though):

> $.parseHTML('<div onclick="a"></div><script></script>')
[<div onclick=?"a">?</div>?]

> $.parseHTML('<div onclick="a"></div><script></script>', document, true)
[<div onclick=?"a">?</div>?, <script>?</script>?]

Also, here's a benchmark from the top answer adjusted to the new reality:

JSbin Link

jQuery 1.9.1

  $.parseHTML:    88ms
  $($.parseHTML): 240ms
  <div></div>:    138ms
  <div>:          143ms
  createElement:  64ms

It looks like parseHTML is much closer to createElement than $(), but all the boost is gone after wrapping the results in a new jQuery object


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 html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to dhtml

Child element click event trigger the parent click event Change :hover CSS properties with JavaScript Modifying a query string without reloading the page Adding and removing style attribute from div with jquery Set content of HTML <span> with Javascript jQuery get the id/value of <li> element after click function Capture iframe load complete event How do I attach events to dynamic HTML elements with jQuery? How do I programmatically click on an element in JavaScript? Getting all selected checkboxes in an array