clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Different methods to make DOM elements in jQuery

Filed under: JavaScript— Tagged with: jquery

4 different ways to create HTML element in jQuery.

Method #1, the obvious method

Where as the following might be enough a lot of the times:

var el = '<a href="http://example.com" class="link" id="link2">Testing</a>'

I sense that it is not really recommended by the community. There are better things.

Method #2, the better method

var $el = $('<a>')
  .addCLass('link')
  .attr('href', 'http://example.com')
  .attr('id', 'link2')
  .text('Testing')

Or, same thing but just easier to read:

var $el = $('<a>')
  .addCLass('link')
  .attr('href', 'http://example.com')
  .attr('id', 'link2')
  .text('Testing')

Method #3, the also very nice method

This was added in jQuery 1.4.

var $el = $('<a/>', {
  id: 'link2',
  class: 'link',
  href: 'http://example.com',
  title: 'This is a test',
  rel: 'external',
  text: 'Testing'
})

Method #4, the fastest method

This resonates positively in my programmer monkey brain. According to JsPerf the following method is also the fastest (if that's important to you).

var $e = $(document.createElement('div'))

$e.addClass('foo module')
  .attr('name', 'bob')
  .text('This div is created with jQuery and inserted here.')
  .insertAfter('#module')

Scorecard

document.createElement is clearly fastest of these methods. Here's a JsPerf scorecard:

A bar graph showing the speed difference between jQUery and vanilla JavaScript
JSPerf test results for documentCreate element

Demo

Little demo never hurt anybody. The method #4 in action here.

See a Demo PwWQBK

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!