In version 1.3.2 of jQuery, the following works:
$('<span/>').append(
$([
$('<span/>').append(
$('<a>').attr('href', 'http://google.com').text('Google')
),
$('<span/>').text('Foo')
])
)
It seems that in jQuery 1.4.2, the $([…]) fails silently. I need this code to be compatible with both versions of jQuery since our unit tests are forced to run 1.3.2, but the main application uses jQuery 1.4.2. Any ideas?
Try using
.get(0)to grab the actual element to be added to the array. Seems to work:Try it out: http://jsfiddle.net/TFY22/
(You can switch the jQuery version on the left in jsFiddle, then click Run at the top.)
EDIT: With regard to the comments below, there are simpler approaches.
This will create the entire structure at once.
If you have any dynamic data to include, you can concatenate it in, just be aware that there are security concerns if the source of the data is unknown.
http://jsfiddle.net/TFY22/1/
Or take a more verbose approach, and create each element separately, and append:
http://jsfiddle.net/TFY22/2/
Or chain your
.append()calls to give a structured appearance:http://jsfiddle.net/TFY22/4/