# Different methods to make DOM elements in jQuery

Four different ways to create an HTML element in jQuery.

## Method &#35;1, the obvious method

The following may be enough much of the time:

```js
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 &#35;2, the better method

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

Or, same thing but just easier to read:

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

## Method &#35;3, the also very nice method

This was added in jQuery 1.4.

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

## Method &#35;4, the fastest method

This resonates positively in my programmer monkey brain.
[According to JsPerf](http://jsperf.com/jquery-element-creationyay/3) the
following method is also the fastest (if that's important to you).

```js
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](/images/document-create-element-speed.png)

JSPerf test results for documentCreate element

## Demo

A little demo never hurt anybody. Here is method &#35;4 in action.

[CodePen](https://codepen.io/hilja/pen/PwWQBK)
