A good[ish] website
Web development blog, loads of UI and JavaScript topics
4 different ways to create HTML element in jQuery.
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.
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')
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'
})
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')
document.createElement
is clearly fastest of these methods. Here's a JsPerf scorecard:
Little demo never hurt anybody. The method #4 in action here.
Comments would go here, but the commenting system isn’t ready yet, sorry.