jQuery document.createElement equivalent?

Viewed 1004114

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.

14 Answers

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

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.

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:

const mountpoint = 'https://jsonplaceholder.typicode.com/users'

const $button = $('button')
const $tbody = $('tbody')

const loadAndRender = () => {
  $.getJSON(mountpoint).then(data => {

    $.each(data, (index, { id, username, name, email }) => {
      let row = $('<tr>')
        .append($('<td>', { text: id }))
        .append($('<td>', {
          text: username,
          class: 'click-me',
          on: {
            click: _ => {
              console.log(name)
            }
          }
        }))
        .append($('<td>', { text: email }))

      $tbody.append(row)
    })

  })
}

$button.on('click', loadAndRender)
.click-me {
  background-color: lightgrey
}
<table style="width: 100%">
  <thead>
    <tr>
      <th>ID</th>
      <th>Username</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
  
  </tbody>
</table>

<button>Load and render</button>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

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

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)

Related