views:

836

answers:

3

What I'm trying to do is to create a table pager control using jQuery. It contains lots of links and spans. I've managed to do this with plain string concatenation, but I can't believe that jQuery can't make this more elegant. I can't use jTemplates here since the generation has quite a bit of procedural logic.

Question: is there a way to create an array of HTML elements with jQuery and append them to some container?

Thanks.

+7  A: 

$([$('First Element'), $('Second Element')]).appendTo($('body'))

craigsrose
+3  A: 

There is always append().

$('#container').append('<span>foobar baz</span>');

It seems to me that just using string concatenation and append would be the least complex, and probably fastest option. However, following is an untested example of a way to (arguably) simplify the creation of elements, and allow you to append them to a given parent element:

function elemCreate(type, content, attrs) {
   /* type: string tag name
    * content: string element content
    * attrs: associative array of attrs and values
    */
    elem = '<' + type + '></' + type + '>'
    e = $(elem).attr(attrs)
    e.append(content)
    return e
}

stuff = [];    
stuff.push(elemCreate('a', 'Click me!', {'href': 'http://stackoverflow.com'});

$(stuff).appendTo($('#container'));
vezult
+3  A: 

String concatenation (or Array.join) is fine, as long as you make it pretty ;)

var structure = [
    '<div id="something">',
        '<span>Hello!</span>',
    '</div>'
];

$(structure.join('')).appendTo(container);
J-P